List of usage examples for java.lang.reflect Constructor getGenericParameterTypes
@Override
public Type[] getGenericParameterTypes()
From source file:org.unitils.core.context.Context.java
@SuppressWarnings("unchecked") protected <T> T createInstanceOfType(Class<T> type, String... classifiers) { Class<?> implementationType = getImplementationType(type, classifiers); Constructor<?> constructor = getConstructor(implementationType); Object[] arguments;/*from ww w . java 2 s . c o m*/ Class<?>[] parameterTypes; if (constructor == null) { arguments = new Object[0]; parameterTypes = new Class[0]; } else { parameterTypes = constructor.getParameterTypes(); Type[] genericParameterTypes = constructor.getGenericParameterTypes(); Annotation[][] argumentAnnotations = constructor.getParameterAnnotations(); arguments = new Object[parameterTypes.length]; for (int i = 0; i < parameterTypes.length; i++) { arguments[i] = getArgumentInstance(parameterTypes[i], genericParameterTypes[i], argumentAnnotations[i]); } } Object instance = ReflectionUtils.createInstanceOfType(implementationType, true, parameterTypes, arguments); if (instance instanceof Factory) { instance = ((Factory) instance).create(); } if (!type.isAssignableFrom(instance.getClass())) { throw new UnitilsException( "Implementation type " + instance.getClass().getName() + " is not of type " + type.getName()); } return (T) instance; }
From source file:com.basistech.rosette.apimodel.ModelTest.java
private Object createObject(Constructor ctor) { Object o;//from w ww. j ava2s .c o m int argSize = ctor.getParameterTypes().length; Class[] parameterTypes = ctor.getParameterTypes(); Object[] args = new Object[argSize]; for (int i = 0; i < argSize; i++) { try { args[i] = createObjectForType(parameterTypes[i], ctor.getGenericParameterTypes()[i]); } catch (Throwable e) { e.printStackTrace(); fail(String.format("Unable to create object %s %d %s %s", ctor, i, parameterTypes[i], ctor.getGenericParameterTypes()[i])); return null; } } try { o = ctor.newInstance(args); } catch (Throwable t) { if (!Options.class.equals(ctor.getDeclaringClass())) { t.printStackTrace(); fail(String.format("Unable to create object for %s", ctor)); } return null; } return o; }
From source file:org.itest.impl.ITestRandomObjectGeneratorImpl.java
protected Object newInstance(Class<?> clazz, ITestContext iTestContext, Type... typeActualArguments) { Object res;/*from w w w.ja v a 2 s .c o m*/ Constructor<?> c = getConstructor(clazz); final Map<String, Type> map = new HashMap<String, Type>(); TypeVariable<?> typeArguments[] = clazz.getTypeParameters(); for (int i = 0; i < typeActualArguments.length; i++) { map.put(typeArguments[i].getName(), typeActualArguments[i]); } Type[] constructorTypes = c.getGenericParameterTypes(); Object[] constructorArgs = new Object[constructorTypes.length]; for (int i = 0; i < constructorTypes.length; i++) { Type pt = ITestTypeUtil.getTypeProxy(constructorTypes[i], map); iTestContext.enter(iTestContext.getCurrentOwner(), "<init[" + i + "]>"); iTestContext.setEmptyParam(); constructorArgs[i] = generateRandom(pt, Collections.EMPTY_MAP, iTestContext); iTestContext.leave(constructorArgs[i]); } try { res = c.newInstance(constructorArgs); } catch (Exception e) { // Object[] args = new Object[constructorArgs.length + 1]; // args[0] = generateRandom(clazz.getEnclosingClass(), null, null, owner, postProcess); // System.arraycopy(constructorArgs, 0, args, 1, constructorArgs.length); // try { // res = c.newInstance(args); // } catch (Exception ee) { // throw new RuntimeException(ee); // } throw new RuntimeException(e); } return res; }
From source file:com.google.dexmaker.ProxyBuilder.java
/** * Create a new instance of the class to proxy. * //from w w w . j a va 2s. c o m * @throws UnsupportedOperationException * if the class we are trying to create a proxy for is not accessible. * @throws IOException * if an exception occurred writing to the {@code dexCache} directory. * @throws UndeclaredThrowableException * if the constructor for the base class to proxy throws a declared exception during construction. * @throws IllegalArgumentException * if the handler is null, if the constructor argument types do not match the constructor argument values, or if no such constructor exists. */ public T build(Application application) throws IOException { this.application = application; if (handler == null) { throw new IllegalArgumentException("handler == null"); } if (constructorArgTypes.length != constructorArgValues.length) { throw new IllegalArgumentException("constructorArgValues.length != constructorArgTypes.length"); } Class<? extends T> proxyClass = buildProxyClass(); if (proxyClass == null) { return null; } Constructor<? extends T> constructor = null; try { constructor = proxyClass.getConstructor(constructorArgTypes); } catch (NoSuchMethodException e) { Constructor[] constructors = proxyClass.getConstructors(); for (Constructor constructor2 : constructors) { if (constructor2.getGenericParameterTypes().length == constructorArgTypes.length) { constructor = constructor2; break; } } } T result; try { result = constructor.newInstance(constructorArgValues); } catch (InstantiationException e) { // Should not be thrown, generated class is not abstract. throw new AssertionError(e); } catch (IllegalAccessException e) { // Should not be thrown, the generated constructor is accessible. throw new AssertionError(e); } catch (InvocationTargetException e) { // Thrown when the base class constructor throws an exception. throw launderCause(e); } setHandlerInstanceField(result, handler); return result; }
From source file:org.evosuite.setup.TestUsageChecker.java
public static boolean canUse(Constructor<?> c) { if (c.isSynthetic()) { return false; }/*w ww .j av a2s . co m*/ // synthetic constructors are OK if (Modifier.isAbstract(c.getDeclaringClass().getModifiers())) return false; // TODO we could enable some methods from Object, like getClass //if (c.getDeclaringClass().equals(java.lang.Object.class)) // return false;// handled here to avoid printing reasons if (c.getDeclaringClass().equals(java.lang.Thread.class)) return false;// handled here to avoid printing reasons if (c.getDeclaringClass().isAnonymousClass()) return false; if (c.getDeclaringClass().isLocalClass()) { logger.debug("Skipping constructor of local class " + c.getName()); return false; } if (c.getDeclaringClass().isMemberClass() && !TestUsageChecker.canUse(c.getDeclaringClass())) return false; if (!Properties.USE_DEPRECATED && c.isAnnotationPresent(Deprecated.class)) { final Class<?> targetClass = Properties.getTargetClassAndDontInitialise(); if (Properties.hasTargetClassBeenLoaded() && !c.getDeclaringClass().equals(targetClass)) { logger.debug("Excluding deprecated constructor " + c.getName()); return false; } } if (isForbiddenNonDeterministicCall(c)) { return false; } if (Modifier.isPublic(c.getModifiers())) { TestClusterUtils.makeAccessible(c); return true; } for (java.lang.reflect.Type paramType : c.getGenericParameterTypes()) { if (!canUse(paramType)) return false; } // If default access rights, then check if this class is in the same package as the target class if (!Modifier.isPrivate(c.getModifiers())) { // && !Modifier.isProtected(c.getModifiers())) { String packageName = ClassUtils.getPackageName(c.getDeclaringClass()); if (packageName.equals(Properties.CLASS_PREFIX)) { TestClusterUtils.makeAccessible(c); return true; } } return false; }
From source file:org.restlet.ext.jaxrs.internal.wrappers.params.ParameterList.java
/** * @param constr//from ww w. j a v a2 s . co m * @param tlContext * @param leaveEncoded * @param jaxRsProviders * @param extensionBackwardMapping * @param paramsAllowed * @param logger * @param allMustBeAvailable * @throws MissingAnnotationException * @throws IllegalTypeException * if one of the parameters contains a @{@link Context} on * an type that must not be annotated with @{@link Context}. * @throws IllegalPathParamTypeException */ public ParameterList(Constructor<?> constr, ThreadLocalizedContext tlContext, boolean leaveEncoded, JaxRsProviders jaxRsProviders, ExtensionBackwardMapping extensionBackwardMapping, boolean paramsAllowed, Logger logger, boolean allMustBeAvailable) throws MissingAnnotationException, IllegalTypeException, IllegalPathParamTypeException { this(constr.getParameterTypes(), constr.getGenericParameterTypes(), constr.getParameterAnnotations(), tlContext, leaveEncoded, jaxRsProviders, extensionBackwardMapping, paramsAllowed, false, logger, allMustBeAvailable); }
From source file:dinistiq.Dinistiq.java
/** * Creates an instance of the given type and registeres it with the container. * * @param dependencies dependencies within the scope * @param cls type to create an instance of * @param beanName beans name in the scope using the given dependencies *//* w w w . j a v a 2 s .c o m*/ private <T extends Object> T createInstance(Map<String, Set<Object>> dependencies, Class<T> cls, String beanName) throws Exception { LOG.info("createInstance({})", cls.getSimpleName()); Constructor<?> c = null; Constructor<?>[] constructors = cls.getDeclaredConstructors(); LOG.debug("createInstance({}) constructors.length={}", cls.getSimpleName(), constructors.length); for (Constructor<?> ctor : constructors) { LOG.debug("createInstance({}) {}", cls.getSimpleName(), ctor); c = (ctor.getAnnotation(Inject.class) != null) ? ctor : c; } // for c = (c == null) ? cls.getConstructor() : c; // Don't record constructor dependencies - they MUST be already fulfilled Object[] parameters = getParameters(null, null, beanName, c.getParameterTypes(), c.getGenericParameterTypes(), c.getParameterAnnotations()); dependencies.put(beanName, new HashSet<>()); boolean accessible = c.isAccessible(); try { c.setAccessible(true); return convert(c.newInstance(parameters)); } finally { c.setAccessible(accessible); } // try/finally }
From source file:org.openTwoFactor.client.util.TwoFactorClientCommonUtils.java
/** * Construct a class//from ww w . java 2 s.com * @param <T> template type * @param theClass * @param allowPrivateConstructor true if should allow private constructors * @return the instance */ public static <T> T newInstance(Class<T> theClass, boolean allowPrivateConstructor) { if (!allowPrivateConstructor) { return newInstance(theClass); } try { Constructor<?>[] constructorArray = theClass.getDeclaredConstructors(); for (Constructor<?> constructor : constructorArray) { if (constructor.getGenericParameterTypes().length == 0) { if (allowPrivateConstructor) { constructor.setAccessible(true); } return (T) constructor.newInstance(); } } //why cant we find a constructor??? throw new RuntimeException("Why cant we find a constructor for class: " + theClass); } catch (Throwable e) { if (theClass != null && Modifier.isAbstract(theClass.getModifiers())) { throw new RuntimeException("Problem with class: " + theClass + ", maybe because it is abstract!", e); } throw new RuntimeException("Problem with class: " + theClass, e); } }