List of usage examples for java.lang Class getConstructors
@CallerSensitive public Constructor<?>[] getConstructors() throws SecurityException
From source file:com.oltpbenchmark.util.ClassUtil.java
/** * //from w ww . j av a 2s. co m * @param <T> * @param target_class * @param params * @return */ @SuppressWarnings("unchecked") public static <T> Constructor<T> getConstructor(Class<T> target_class, Class<?>... params) { NoSuchMethodException error = null; try { return (target_class.getConstructor(params)); } catch (NoSuchMethodException ex) { // The first time we get this it can be ignored // We'll try to be nice and find a match for them error = ex; } assert (error != null); if (LOG.isDebugEnabled()) { LOG.debug("TARGET CLASS: " + target_class); LOG.debug("TARGET PARAMS: " + Arrays.toString(params)); } List<Class<?>> paramSuper[] = (List<Class<?>>[]) new List[params.length]; for (int i = 0; i < params.length; i++) { paramSuper[i] = ClassUtil.getSuperClasses(params[i]); if (LOG.isDebugEnabled()) LOG.debug(" SUPER[" + params[i].getSimpleName() + "] => " + paramSuper[i]); } // FOR for (Constructor<?> c : target_class.getConstructors()) { Class<?> cTypes[] = c.getParameterTypes(); if (LOG.isDebugEnabled()) { LOG.debug("CANDIDATE: " + c); LOG.debug("CANDIDATE PARAMS: " + Arrays.toString(cTypes)); } if (params.length != cTypes.length) continue; for (int i = 0; i < params.length; i++) { List<Class<?>> cSuper = ClassUtil.getSuperClasses(cTypes[i]); if (LOG.isDebugEnabled()) LOG.debug(" SUPER[" + cTypes[i].getSimpleName() + "] => " + cSuper); if (CollectionUtils.intersection(paramSuper[i], cSuper).isEmpty() == false) { return ((Constructor<T>) c); } } // FOR (param) } // FOR (constructors) throw new RuntimeException("Failed to retrieve constructor for " + target_class.getSimpleName(), error); }
From source file:ch.algotrader.config.ConfigBeanFactory.java
@SuppressWarnings("unchecked") public <T> T create(final ConfigParams configParams, final Class<T> clazz) { Validate.notNull(configParams, "ConfigParams is null"); Validate.notNull(clazz, "Target class is null"); Constructor<?>[] constructors = clazz.getConstructors(); if (constructors.length != 1) { throw new ConfigBeanCreationException( clazz.getName() + " config bean class is expected to declare one constructor only"); }// ww w .j a v a 2 s .c o m Constructor<?> constructor = constructors[0]; Annotation[][] parameterAnnotations = constructor.getParameterAnnotations(); Class<?>[] parameterTypes = constructor.getParameterTypes(); if (parameterTypes.length != parameterAnnotations.length) { throw new ConfigBeanCreationException(clazz.getName() + " config bean metadata is inconsistent"); } Object[] paramValues = new Object[parameterTypes.length]; for (int i = 0; i < parameterTypes.length; i++) { Class<?> paramType = parameterTypes[i]; Annotation[] annotations = parameterAnnotations[i]; ConfigName configName = null; for (Annotation annotation : annotations) { if (annotation.annotationType().equals(ConfigName.class)) { configName = (ConfigName) annotation; break; } } if (configName == null) { throw new ConfigBeanCreationException( clazz.getName() + " config bean parameter does not have mandatory metadata"); } Object paramValue = configParams.getParameter(configName.value(), paramType); if (paramValue == null && !configName.optional()) { throw new ConfigBeanCreationException("Config parameter '" + configName.value() + "' is undefined"); } paramValues[i] = paramValue; } try { return (T) constructor.newInstance(paramValues); } catch (InstantiationException | InvocationTargetException | IllegalAccessException ex) { throw new ConfigBeanCreationException(ex); } }
From source file:sx.blah.discord.SpoofBot.java
/** * Randomly constructs an object./*w w w. j a v a 2s. c om*/ * * @param client The discord client. * @param clazz The class to construct. * @param <T> The type of object to construct. * @return The constructed object (or null if not possible). * * @throws IllegalAccessException * @throws InvocationTargetException * @throws InstantiationException */ public static <T> T randomizeObject(IDiscordClient client, Class<T> clazz) throws IllegalAccessException, InvocationTargetException, InstantiationException { if (canBeRandomized(clazz)) { if (String.class.isAssignableFrom(clazz)) return (T) getRandString(); else if (Character.class.isAssignableFrom(clazz)) return (T) getRandCharacter(); else if (Boolean.class.isAssignableFrom(clazz)) return (T) getRandBoolean(); else if (Number.class.isAssignableFrom(clazz)) return (T) getRandNumber((Class<? extends Number>) clazz); else if (Void.class.isAssignableFrom(clazz)) return null; else if (IDiscordClient.class.isAssignableFrom(clazz)) return (T) client; } else { outer: for (Constructor constructor : clazz.getConstructors()) { Object[] parameters = new Object[constructor.getParameterCount()]; for (Class<?> param : constructor.getParameterTypes()) { if (!canBeRandomized(param)) continue outer; } if (parameters.length > 0) { for (int i = 0; i < parameters.length; i++) { parameters[i] = randomizeObject(client, constructor.getParameterTypes()[i]); } return (T) constructor.newInstance(parameters); } else { return (T) constructor.newInstance(); } } } return null; }
From source file:org.jbpm.formModeler.core.model.PojoDataHolder.java
protected Object createInstance(Class pojoClass) throws Exception { for (Constructor constructor : pojoClass.getConstructors()) { if (constructor.getParameterTypes().length == 0) { return constructor.newInstance(); }//from ww w . j a v a2 s .c o m } return null; }
From source file:de.xirp.plugin.PluginManager.java
/** * Gets an instance of a plugin which is specified by the * PluginInfo Object by using a class loader for this plugin. * //from w w w . ja v a 2 s . com * @param info * Information about the plugin * @param robotName * name of the robot this plugin is for * @return Instance of the requested plugin * @throws Exception * exception when loading the plugin */ @SuppressWarnings("unchecked") protected static SecurePluginView getInstance(PluginInfo info, String robotName) throws Exception { // try { URLClassLoader classLoader = getClassLoader(info); Class<IPlugable> claas = (Class<IPlugable>) Class.forName(info.getMainClass(), true, classLoader); Constructor[] constructors = claas.getConstructors(); Constructor useConstructor = null; for (Constructor constructor : constructors) { Class[] types = constructor.getParameterTypes(); if (types.length == 2) { // Locale locale = new Locale(""); if ((types[0] == String.class) && (types[1] == PluginInfo.class)) { useConstructor = constructor; break; } } else if (types.length == 2) { if ((types[0] == PluginInfo.class)) { useConstructor = constructor; break; } } } if (useConstructor == null) { logClass.error(I18n.getString("PluginManager.log.pluginCouldNotBeInstanciatedNoConstructorFound", //$NON-NLS-1$ info.getMainClass())); } else { Object[] arglist = new Object[useConstructor.getParameterTypes().length]; if (arglist.length == 2) { arglist[0] = robotName; arglist[1] = info; } else if (arglist.length == 1) { arglist[0] = info; } IPlugable plugin = (IPlugable) useConstructor.newInstance(arglist); return new SecurePluginView(plugin); } return null; }
From source file:org.jsonschema2pojo.integration.config.UseInnerClassBuildersIT.java
/** * This method confirms that by default the only constructor available to a builder is the empty argument constructor *//*from w ww. java2s . c om*/ @Test public void innerBuilderExtraConstructorsRequireConfig() throws ClassNotFoundException { ClassLoader resultsClassLoader = schemaRule.generateAndCompile("/schema.useInnerClassBuilders/child.json", "com.example", config("generateBuilders", true, "useInnerClassBuilders", true)); Class<?> builderClass = resultsClassLoader.loadClass("com.example.Child$ChildBuilder"); assertEquals(1, builderClass.getConstructors().length); Constructor<?> constructor = builderClass.getConstructors()[0]; assertEquals(0, constructor.getParameterCount()); }
From source file:jetbrains.buildServer.server.rest.util.BeanFactory.java
@Nullable private <T> Constructor<T> findConstructor(@NotNull final Class<T> clazz, Class<?>[] argTypes) { try {/*from ww w .j a va 2 s . co m*/ return clazz.getConstructor(argTypes); } catch (NoSuchMethodException e) { //NOP } for (Constructor c : clazz.getConstructors()) { final Class[] reqTypes = c.getParameterTypes(); if (checkParametersMatch(argTypes, reqTypes)) { //noinspection unchecked return (Constructor<T>) c; } } return null; }
From source file:fitnesse.slim.StatementExecutor.java
private Object createInstanceOfConstructor(String className, Object[] args) throws IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException { Class<?> k = searchPathsForClass(className); Constructor<?> constructor = getConstructor(k.getConstructors(), args); if (constructor == null) throw new SlimError(String.format("message:<<NO_CONSTRUCTOR %s>>", className)); Object newInstance = newInstance(args, constructor); if (newInstance instanceof StatementExecutorConsumer) { ((StatementExecutorConsumer) newInstance).setStatementExecutor(this); }/*from ww w.j a va 2s . c o m*/ return newInstance; }
From source file:org.jdto.impl.AnnotationBeanInspector.java
@Override Constructor findAppropiateConstructor(Class beanClass) { Constructor[] beanConstructors = beanClass.getConstructors(); for (Constructor constructor : beanConstructors) { if (constructor.isAnnotationPresent(DTOConstructor.class)) { return constructor; }/*from w w w . java2 s . co m*/ } if (beanConstructors != null && beanConstructors.length > 0) { //return the last constructor. return beanConstructors[beanConstructors.length - 1]; } else { return null; } }
From source file:com.cloudera.livy.client.common.TestHttpMessages.java
/** * Tests that all defined messages can be serialized and deserialized using Jackson. *//*from ww w .ja v a 2 s . c om*/ @Test public void testMessageSerialization() throws Exception { ObjectMapper mapper = new ObjectMapper(); for (Class<?> msg : HttpMessages.class.getClasses()) { if (msg.isInterface()) { continue; } String name = msg.getSimpleName(); Constructor c = msg.getConstructors()[0]; Object[] params = new Object[c.getParameterTypes().length]; Type[] genericTypes = c.getGenericParameterTypes(); for (int i = 0; i < params.length; i++) { params[i] = dummyValue(c.getParameterTypes()[i], genericTypes[i]); } Object o1 = c.newInstance(params); byte[] serialized = mapper.writeValueAsBytes(o1); Object o2 = mapper.readValue(serialized, msg); assertNotNull("could not deserialize " + name, o2); for (Field f : msg.getFields()) { checkEquals(name, f, o1, o2); } } }