List of usage examples for java.lang Class getConstructors
@CallerSensitive public Constructor<?>[] getConstructors() throws SecurityException
From source file:com.espertech.esper.util.MethodResolver.java
public static Constructor resolveCtor(Class declaringClass, Class[] paramTypes) throws EngineNoSuchCtorException { // Get all the methods for this class Constructor[] ctors = declaringClass.getConstructors(); Constructor bestMatch = null; int bestConversionCount = -1; // Examine each method, checking if the signature is compatible Constructor conversionFailedCtor = null; for (Constructor ctor : ctors) { // Check the modifiers: we only want public if (!Modifier.isPublic(ctor.getModifiers())) { continue; }/*from w w w. jav a 2s.c o m*/ // Check the parameter list int conversionCount = compareParameterTypesNoContext(ctor.getParameterTypes(), paramTypes, null, null, ctor.getGenericParameterTypes()); // Parameters don't match if (conversionCount == -1) { conversionFailedCtor = ctor; continue; } // Parameters match exactly if (conversionCount == 0) { bestMatch = ctor; break; } // No previous match if (bestMatch == null) { bestMatch = ctor; bestConversionCount = conversionCount; } else { // Current match is better if (conversionCount < bestConversionCount) { bestMatch = ctor; bestConversionCount = conversionCount; } } } if (bestMatch != null) { return bestMatch; } else { StringBuilder parameters = new StringBuilder(); String message = "Constructor not found for " + declaringClass.getSimpleName() + " taking "; if (paramTypes != null && paramTypes.length != 0) { String appendString = ""; for (Object param : paramTypes) { parameters.append(appendString); if (param == null) { parameters.append("(null)"); } else { parameters.append(param.toString()); } appendString = ", "; } message += "('" + parameters + "')'"; } else { message += "no parameters"; } throw new EngineNoSuchCtorException(message, conversionFailedCtor); } }
From source file:Main.java
private static void loadProviderIfNecessary(String providerClassName) { if (providerClassName == null) { return;/*from www .j a va2s . c o m*/ } final Class<?> klass; try { final ClassLoader sysLoader = ClassLoader.getSystemClassLoader(); if (sysLoader != null) { klass = sysLoader.loadClass(providerClassName); } else { klass = Class.forName(providerClassName); } } catch (ClassNotFoundException e) { e.printStackTrace(); System.exit(1); return; } Constructor<?> constructor = null; for (Constructor<?> c : klass.getConstructors()) { if (c.getParameterTypes().length == 0) { constructor = c; break; } } if (constructor == null) { System.err.println("No zero-arg constructor found for " + providerClassName); System.exit(1); return; } final Object o; try { o = constructor.newInstance(); } catch (Exception e) { e.printStackTrace(); System.exit(1); return; } if (!(o instanceof Provider)) { System.err.println("Not a Provider class: " + providerClassName); System.exit(1); } Security.insertProviderAt((Provider) o, 1); }
From source file:org.hibernate.internal.util.ReflectHelper.java
/** * Retrieve a constructor for the given class, with arguments matching the specified Hibernate mapping * {@link Type types}.//from w ww .j a va 2 s .c o m * * @param clazz The class needing instantiation * @param types The types representing the required ctor param signature * @return The matching constructor. * @throws PropertyNotFoundException Indicates we could not locate an appropriate constructor (todo : again with PropertyNotFoundException???) */ public static Constructor getConstructor(Class clazz, Type[] types) throws PropertyNotFoundException { final Constructor[] candidates = clazz.getConstructors(); for (int i = 0; i < candidates.length; i++) { final Constructor constructor = candidates[i]; final Class[] params = constructor.getParameterTypes(); if (params.length == types.length) { boolean found = true; for (int j = 0; j < params.length; j++) { final boolean ok = params[j].isAssignableFrom(types[j].getReturnedClass()) || (types[j] instanceof PrimitiveType && params[j] == ((PrimitiveType) types[j]).getPrimitiveClass()); if (!ok) { found = false; break; } } if (found) { constructor.setAccessible(true); return constructor; } } } throw new PropertyNotFoundException("no appropriate constructor in class: " + clazz.getName()); }
From source file:io.github.benas.randombeans.util.ReflectionUtils.java
@SuppressWarnings("unchecked") public static <T> Randomizer<T> newInstance(final Class<T> type, final RandomizerArgument[] randomizerArguments) { try {/* w ww.ja va2 s . c o m*/ if (notEmpty(randomizerArguments)) { Optional<Constructor<?>> matchingConstructor = asList(type.getConstructors()).stream() .filter(constructor -> hasSameArgumentNumber(constructor, randomizerArguments) && hasSameArgumentTypes(constructor, randomizerArguments)) .findFirst(); if (matchingConstructor.isPresent()) { return (Randomizer<T>) matchingConstructor.get() .newInstance(convertArguments(randomizerArguments)); } } return (Randomizer<T>) type.newInstance(); } catch (IllegalAccessException | InvocationTargetException | InstantiationException e) { throw new ObjectGenerationException( format("Could not create Randomizer of type: %s with constructor arguments: %s", type, Arrays.toString(randomizerArguments)), e); } }
From source file:com.swingtech.commons.testing.JavaBeanTester.java
private static Object buildValue(Class<?> clazz) throws InstantiationException, IllegalAccessException, IllegalArgumentException, SecurityException, InvocationTargetException { // If we are using a Mocking framework try that first... final Object mockedObject = buildMockValue(clazz); if (mockedObject != null) { return mockedObject; }/*from w ww .j a v a2s . c o m*/ // Next check for a no-arg constructor final Constructor<?>[] ctrs = clazz.getConstructors(); for (Constructor<?> ctr : ctrs) { if (ctr.getParameterTypes().length == 0) { // The class has a no-arg constructor, so just call it return ctr.newInstance(); } } // Specific rules for common classes if (clazz == String.class) { return "testvalue"; } else if (clazz.isArray()) { return Array.newInstance(clazz.getComponentType(), 1); } else if (clazz == boolean.class || clazz == Boolean.class) { return true; } else if (clazz == int.class || clazz == Integer.class) { return 1; } else if (clazz == long.class || clazz == Long.class) { return 1L; } else if (clazz == double.class || clazz == Double.class) { return 1.0D; } else if (clazz == float.class || clazz == Float.class) { return 1.0F; } else if (clazz == char.class || clazz == Character.class) { return 'Y'; // Add your own rules here } else { fail("Unable to build an instance of class " + clazz.getName() + ", please add some code to the " + JavaBeanTester.class.getName() + " class to do this."); return null; // for the compiler } }
From source file:org.eiichiro.bootleg.Types.java
/** * Returns <code>true</code> if the specified type is an user define value * type./*from ww w .j a va 2s . c o m*/ * User defined value type must satisfy either of the following condition. * <ol> * <li>(The class) has a public constructor that takes one String.class parameter.</li> * <li>Has a public static factory method that named 'valueOf' and takes one * String.class parameter.</li> * </ol> * * @param type The type to be tested. * @return <code>true</code> if the specified type is an user define value * type. */ public static boolean isUserDefinedValueType(Type type) { Class<?> rawType = getRawType(type); if (rawType == null) { return false; } for (Constructor<?> constructor : rawType.getConstructors()) { Class<?>[] parameterTypes = constructor.getParameterTypes(); if (parameterTypes.length == 1 && parameterTypes[0].equals(String.class)) { return true; } } for (Method method : rawType.getMethods()) { if (method.getName().equals("valueOf") && Modifier.isStatic(method.getModifiers())) { return true; } } return false; }
From source file:com.konakart.apiexamples.BaseApiExample.java
/** * Utility method to instantiate an engine instance. The class name of the engine is passed in * as a parameter so this method may be used to instantiate a POJO engine, a SOAP engine, an RMI * engine or a JSON engine./*from w ww.j a v a 2 s .c om*/ * * @param engineClassName * @param config * @return Returns an Engine Instance * @throws IllegalArgumentException * @throws InstantiationException * @throws IllegalAccessException * @throws InvocationTargetException * @throws ClassNotFoundException */ protected static KKEngIf getKKEngByName(String engineClassName, EngineConfig config) throws IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException, ClassNotFoundException { Class<?> engineClass = Class.forName(engineClassName); KKEngIf kkeng = null; Constructor<?>[] constructors = engineClass.getConstructors(); Constructor<?> engConstructor = null; if (constructors != null && constructors.length > 0) { for (int i = 0; i < constructors.length; i++) { Constructor<?> constructor = constructors[i]; Class<?>[] parmTypes = constructor.getParameterTypes(); if (parmTypes != null && parmTypes.length == 1) { String parmName = parmTypes[0].getName(); if (parmName != null && parmName.equals("com.konakart.appif.EngineConfigIf")) { engConstructor = constructor; } } } } if (engConstructor != null) { kkeng = (KKEngIf) engConstructor.newInstance(config); } return kkeng; }
From source file:org.openehr.build.RMObjectBuilder.java
private static Constructor fullConstructor(Class klass) { Constructor[] array = klass.getConstructors(); for (Constructor constructor : array) { if (constructor.isAnnotationPresent(FullConstructor.class)) { return constructor; }//www. ja v a 2 s . c om } return null; }
From source file:ru.runa.notifier.util.ClassLoaderUtil.java
public static Object instantiate(String className, Object... params) { try {//from www. ja va 2 s . co m Class<?> clazz = loadClass(className); Class<?>[] paramType; if (params != null) { paramType = new Class[params.length]; for (int i = 0; i < params.length; ++i) { paramType[i] = params[i].getClass(); } } else { paramType = new Class[0]; params = new Object[0]; } Constructor<?> constructor = null; Constructor<?>[] constructors = clazz.getConstructors(); constrLoop: for (Constructor<?> constr : constructors) { Class<?>[] types = constr.getParameterTypes(); if (types.length != paramType.length) { continue; } for (int i = 0; i < types.length; ++i) { if (!types[i].isAssignableFrom(params[i].getClass())) { continue constrLoop; } } constructor = constr; } if (constructor == null) { constructor = clazz.getConstructor(paramType); } return constructor.newInstance(params); } catch (Exception e) { throw Throwables.propagate(e); } }
From source file:it.unibo.alchemist.language.EnvironmentBuilder.java
@SuppressWarnings("unchecked") private static <Klazz> List<Constructor<Klazz>> unsafeExtractConstructors(final Class<?> clazz) { final Constructor<?>[] constructors = clazz.getConstructors(); final List<Constructor<Klazz>> list = new ArrayList<Constructor<Klazz>>(constructors.length); for (final Constructor<?> c : constructors) { list.add((Constructor<Klazz>) c); }/*w w w .ja v a2 s . c om*/ return list; }