List of usage examples for java.lang.reflect Constructor getParameterTypes
@Override
public Class<?>[] getParameterTypes()
From source file:org.jgentleframework.utils.Utils.java
/** * Creates the instance object from the given {@link Constructor}. * /* w w w .ja va2 s . co m*/ * @param provider * the current {@link Provider} * @param constructor * the given {@link Constructor} * @return Object */ public static Object createInstanceFromInjectedConstructor(Provider provider, Constructor<?> constructor) { Object result = null; // Khi to v inject dependency cho parameter Object[] args = new Object[constructor.getParameterTypes().length]; for (int i = 0; i < constructor.getParameterAnnotations().length; i++) { Map<Class<? extends Annotation>, Annotation> annoList = new HashMap<Class<? extends Annotation>, Annotation>(); List<Class<? extends Annotation>> clazzlist = new ArrayList<Class<? extends Annotation>>(); for (Annotation anno : constructor.getParameterAnnotations()[i]) { annoList.put(anno.annotationType(), anno); clazzlist.add(anno.annotationType()); } if (!clazzlist.contains(Inject.class)) { args[i] = null; } else { args[i] = InOutExecutor.getInjectedDependency((Inject) annoList.get(Inject.class), constructor.getParameterTypes()[i], provider); } } try { constructor.setAccessible(true); result = constructor.newInstance(args); } catch (Exception e) { if (log.isFatalEnabled()) { log.fatal("Could not new instance on this constructor [" + constructor + "]", e); } } return result; }
From source file:org.paxml.util.ReflectUtils.java
/** * Construct object from class using the default constructor. * /*from w w w. j a va2 s . c om*/ * @param <T> * the class type * @param clazz * the class * @param constructParams * the parameters to call constructor with * @return the object * @throws RuntimeException * if the construction fails. */ public static <T> T createObject(Class<? extends T> clazz, Object... constructParams) { Constructor<T> con = null; Class[] argTypes = null; for (Constructor c : clazz.getDeclaredConstructors()) { argTypes = c.getParameterTypes(); if (argTypes.length == constructParams.length) { con = c; break; } } if (con == null) { throw new PaxmlRuntimeException("No constructor found with " + constructParams.length + " parameters!"); } try { Object[] args = new Object[constructParams.length]; for (int i = args.length - 1; i >= 0; i--) { args[i] = coerceType(constructParams[i], argTypes[i]); } con.setAccessible(true); return con.newInstance(args); } catch (Exception e) { throw new PaxmlRuntimeException("Cannot create instance from class: " + clazz.getName(), e); } }
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 . j a v a2 s. 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:at.ac.tuwien.infosys.jcloudscale.utility.ReflectionUtil.java
/** * Returns a {@link Constructor} object that reflects the specified constructor of the given type. * <p/>//w ww . j ava2s . c o m * If no parameter types are specified i.e., {@code paramTypes} is {@code null} or empty, the default constructor * is returned.<br/> * If a parameter type is not known i.e., it is {@code null}, all declared constructors are checked whether their * parameter types conform to the known parameter types i.e., if every known type is assignable to the parameter * type of the constructor and if exactly one was found, it is returned.<br/> * Otherwise a {@link NoSuchMethodException} is thrown indicating that no or several constructors were found. * * @param type the class * @param paramTypes the full-qualified class names of the parameters (can be {@code null}) * @param classLoader the class loader to use * @return the accessible constructor resolved * @throws NoSuchMethodException if there are zero or more than one constructor candidates * @throws ClassNotFoundException if a class cannot be located by the specified class loader */ @SuppressWarnings("unchecked") public static <T> Constructor<T> findConstructor(Class<T> type, Class<?>... clazzes) throws NoSuchMethodException, ClassNotFoundException { Constructor<T> constructor = null; // If all parameter types are known, find the constructor that exactly matches the signature if (!ArrayUtils.contains(clazzes, null)) { try { constructor = type.getDeclaredConstructor(clazzes); } catch (NoSuchMethodException e) { // Ignore } } // If no constructor was found, find all possible candidates if (constructor == null) { List<Constructor<T>> candidates = new ArrayList<>(1); for (Constructor<T> declaredConstructor : (Constructor<T>[]) type.getDeclaredConstructors()) { if (ClassUtils.isAssignable(clazzes, declaredConstructor.getParameterTypes())) { // Check if there is already a constructor method with the same signature for (int i = 0; i < candidates.size(); i++) { Constructor<T> candidate = candidates.get(i); /** * If all parameter types of constructor A are assignable to the types of constructor B * (at least one type is a subtype of the corresponding parameter), keep the one whose types * are more concrete and drop the other one. */ if (ClassUtils.isAssignable(declaredConstructor.getParameterTypes(), candidate.getParameterTypes())) { candidates.remove(candidate); i--; } else if (ClassUtils.isAssignable(candidate.getParameterTypes(), declaredConstructor.getParameterTypes())) { declaredConstructor = null; break; } } if (declaredConstructor != null) { candidates.add(declaredConstructor); } } } if (candidates.size() != 1) { throw new NoSuchMethodException( String.format("Cannot find distinct constructor for type '%s' with parameter types %s", type, Arrays.toString(clazzes))); } constructor = candidates.get(0); } //do we really need this dependency? //ReflectionUtils.makeAccessible(constructor); if (constructor != null && !constructor.isAccessible()) constructor.setAccessible(true); return constructor; }
From source file:org.janusgraph.diskstorage.cassandra.astyanax.AstyanaxStoreManager.java
@SuppressWarnings("unchecked") private static <V> V instantiate(String policyClassName, Integer[] args, String raw) throws Exception { for (Constructor<?> con : Class.forName(policyClassName).getConstructors()) { Class<?>[] parameterTypes = con.getParameterTypes(); // match constructor by number of arguments first if (args.length != parameterTypes.length) continue; // check if the constructor parameter types are compatible with argument types (which are integer) // note that we allow long.class arguments too because integer is cast to long by runtime. boolean intsOrLongs = true; for (Class<?> pc : parameterTypes) { if (!pc.equals(int.class) && !pc.equals(long.class)) { intsOrLongs = false;/*from w ww .j av a2 s.c o m*/ break; } } // we found a constructor with required number of parameters but times didn't match, let's carry on if (!intsOrLongs) continue; if (log.isDebugEnabled()) log.debug("About to instantiate class {} with {} arguments", con.toString(), args.length); return (V) con.newInstance(args); } throw new Exception( "Failed to identify a class matching the Astyanax Retry Policy config string \"" + raw + "\""); }
From source file:com.google.gdt.eclipse.designer.uibinder.parser.UiBinderParser.java
/** * @return the instance of given {@link Class}, created using the most specific method. *//*from w ww . j a v a 2s. co m*/ private static Object createObjectInstance(UiBinderContext context, String objectName, Class<?> clazz, Object[] args) throws Exception { // try CreateObjectInstance broadcast { Object result[] = { null }; context.getBroadcastSupport().getListener(CreateObjectInstance.class).invoke(objectName, clazz, args, result); if (result[0] != null) { return result[0]; } } // try "UiBinder.createInstance" script { ComponentDescription description = ComponentDescriptionHelper.getDescription(context, clazz); // prepare script String script; { String scriptObject[] = { null }; context.getBroadcastSupport().getListener(CreateObjectScript.class).invoke(objectName, clazz, args, scriptObject); script = scriptObject[0]; } if (script == null) { script = description.getParameter("UiBinder.createInstance"); } // try to use script if (script != null) { ClassLoader classLoader = context.getClassLoader(); Map<String, Object> variables = Maps.newTreeMap(); variables.put("wbpClassLoader", UiBinderParser.class.getClassLoader()); variables.put("classLoader", classLoader); variables.put("componentClass", clazz); variables.put("objectName", objectName); variables.put("modelClass", description.getModelClass()); variables.put("modelClassLoader", description.getModelClass().getClassLoader()); variables.put("args", args); Object result = ScriptUtils.evaluate(classLoader, script, variables); return result; } } // default constructor { Constructor<?> constructor = ReflectionUtils.getConstructorBySignature(clazz, "<init>()"); if (constructor != null) { return constructor.newInstance(); } } // shortest constructor { Constructor<?> constructor = ReflectionUtils.getShortestConstructor(clazz); Class<?>[] parameterTypes = constructor.getParameterTypes(); Object[] argumentValues = new Object[parameterTypes.length]; for (int i = 0; i < parameterTypes.length; i++) { Class<?> parameterType = parameterTypes[i]; argumentValues[i] = getDefaultValue(parameterType); } return constructor.newInstance(argumentValues); } }
From source file:com.impetus.kundera.utils.KunderaCoreUtils.java
/** * @param clazz//from w w w .ja v a 2 s. co m * @return */ public static Object createNewInstance(Class clazz) { Object target = null; try { Constructor[] constructors = clazz.getDeclaredConstructors(); for (Constructor constructor : constructors) { if ((Modifier.isProtected(constructor.getModifiers()) || Modifier.isPublic(constructor.getModifiers())) && constructor.getParameterTypes().length == 0) { constructor.setAccessible(true); target = constructor.newInstance(); constructor.setAccessible(false); break; } } return target; } catch (InstantiationException iex) { logger.error("Error while creating an instance of {} .", clazz); throw new PersistenceException(iex); } catch (IllegalAccessException iaex) { logger.error("Illegal Access while reading data from {}, Caused by: .", clazz, iaex); throw new PersistenceException(iaex); } catch (Exception e) { logger.error("Error while creating an instance of {}, Caused by: .", clazz, e); throw new PersistenceException(e); } }
From source file:it.unibo.alchemist.language.EnvironmentBuilder.java
private static <E> E tryToBuild(final List<Constructor<E>> consList, final List<String> params, final Map<String, Object> env, final RandomGenerator random) throws InstantiationException, IllegalAccessException, InvocationTargetException { for (final Constructor<E> c : consList) { L.debug("Trying to build with constructor " + c); final Class<?>[] args = c.getParameterTypes(); if (args.length == params.size()) { L.debug("Parameters number matches (" + args.length + ")."); final Object[] finalArgs = new Object[args.length]; int i = 0; boolean success = true; for (; i < args.length && success; i++) { final String paramVal = params.get(i); final Class<?> paramClass = args[i]; finalArgs[i] = parseAndCreate(paramClass, paramVal, env, random); if (!paramVal.equals("null") && finalArgs[i] == null) { L.debug("Unable to use this constructor."); success = false;/*from w ww . jav a2s . c o m*/ } } if (success && i == args.length) { final E result = c.newInstance(finalArgs); // L.debug("Created object " + result); return result; } } } throw new IllegalArgumentException("no compatible constructor find for " + params); }
From source file:backtype.storm.utils.Utils.java
public static Object newInstance(String klass, Object... params) { try {//from w w w. j a va 2 s. c o m Class c = Class.forName(klass); Constructor[] constructors = c.getConstructors(); boolean found = false; Constructor con = null; for (Constructor cons : constructors) { if (cons.getParameterTypes().length == params.length) { con = cons; break; } } if (con == null) { throw new RuntimeException( "Cound not found the corresponding constructor, params=" + params.toString()); } else { if (con.getParameterTypes().length == 0) { return c.newInstance(); } else { return con.newInstance(params); } } } catch (Exception e) { throw new RuntimeException(e); } }
From source file:com.helpinput.utils.Utils.java
public static <T> Constructor<?> findConstructor(Class<T> targetClass, Class<?>[] agrsClasses) { Constructor<?>[] constructors = targetClass.getDeclaredConstructors(); Constructor<?> theConstructor = null; for (Constructor<?> constructor : constructors) { Class<?>[] classes = constructor.getParameterTypes(); if (agrsClasses.length == 0 && classes.length == 0) { theConstructor = constructor; break; }//from www. ja va 2s. co m if (agrsClasses.length == classes.length) { for (int i = 0; i < agrsClasses.length; i++) { if (agrsClasses[i] == null) { if (i == agrsClasses.length - 1) { theConstructor = constructor; break; } continue; } if (classes[i].isPrimitive()) { if (!primitiveWrap(classes[i]).isAssignableFrom(agrsClasses[i])) break; } else if (!classes[i].isAssignableFrom(agrsClasses[i])) break; if (i == agrsClasses.length - 1) { theConstructor = constructor; break; } } } if (theConstructor != null) break; } if (null != theConstructor) { if (!theConstructor.isAccessible()) theConstructor.setAccessible(true); return theConstructor; } else { if (targetClass.getSuperclass() != null) { return findConstructor(targetClass.getSuperclass(), agrsClasses); } return null; } }