Java Code Examples for java.lang.reflect.Constructor#getGenericParameterTypes()

The following examples show how to use java.lang.reflect.Constructor#getGenericParameterTypes() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: businessworks   File: TypeLiteral.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Returns the resolved generic parameter types of {@code methodOrConstructor}.
 *
 * @param methodOrConstructor a method or constructor defined by this or any supertype.
 * @since 2.0
 */
public List<TypeLiteral<?>> getParameterTypes(Member methodOrConstructor) {
  Type[] genericParameterTypes;

  if (methodOrConstructor instanceof Method) {
    Method method = (Method) methodOrConstructor;
    checkArgument(method.getDeclaringClass().isAssignableFrom(rawType),
        "%s is not defined by a supertype of %s", method, type);
    genericParameterTypes = method.getGenericParameterTypes();

  } else if (methodOrConstructor instanceof Constructor) {
    Constructor<?> constructor = (Constructor<?>) methodOrConstructor;
    checkArgument(constructor.getDeclaringClass().isAssignableFrom(rawType),
        "%s does not construct a supertype of %s", constructor, type);
    genericParameterTypes = constructor.getGenericParameterTypes();

  } else {
    throw new IllegalArgumentException("Not a method or a constructor: " + methodOrConstructor);
  }

  return resolveAll(genericParameterTypes);
}
 
Example 2
private Pair<Constructor, List<Object>> findConstructor(List<String> arguments) throws
        UiSelectorSyntaxException, UiObjectNotFoundException {
    UiSelectorSyntaxException exThrown = null;
    for (final Constructor constructor : clazz.getConstructors()) {
        try {
            final Type[] parameterTypes = constructor.getGenericParameterTypes();
            final List<Object> args = coerceArgsToTypes(parameterTypes, arguments);
            return new Pair<>(constructor, args);
        } catch (UiSelectorSyntaxException e) {
            exThrown = e;
        }
    }

    throw new UiSelectorSyntaxException(expression.toString(),
            String.format("%s has no suitable constructor with arguments %s",
                    clazz.getSimpleName(), arguments), exThrown);
}
 
Example 3
Source Project: crate   File: TypeLiteral.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Returns the resolved generic parameter types of {@code methodOrConstructor}.
 *
 * @param methodOrConstructor a method or constructor defined by this or any supertype.
 * @since 2.0
 */
public List<TypeLiteral<?>> getParameterTypes(Member methodOrConstructor) {
    Type[] genericParameterTypes;

    if (methodOrConstructor instanceof Method) {
        Method method = (Method) methodOrConstructor;
        if (!method.getDeclaringClass().isAssignableFrom(rawType)) {
            throw new IllegalArgumentException(method + " is not defined by a supertype of " + type);
        }
        genericParameterTypes = method.getGenericParameterTypes();

    } else if (methodOrConstructor instanceof Constructor) {
        Constructor constructor = (Constructor) methodOrConstructor;
        if (!constructor.getDeclaringClass().isAssignableFrom(rawType)) {
            throw new IllegalArgumentException(constructor + " does not construct a supertype of " + type);
        }

        genericParameterTypes = constructor.getGenericParameterTypes();

    } else {
        throw new IllegalArgumentException("Not a method or a constructor: " + methodOrConstructor);
    }

    return resolveAll(genericParameterTypes);
}
 
Example 4
private static Type[] getGenericArray(Constructor<?> constructor)
{
    Type[] genericTypes = constructor.getGenericParameterTypes();
    // for inner classes genericTypes and parameterTypes can be different
    // length, this is a hack to fix this.
    // TODO: investigate this behavior further, on different JVM's and
    // compilers
    if (genericTypes.length < constructor.getParameterTypes().length)
    {
        genericTypes = new Type[constructor.getParameterTypes().length];
        genericTypes[0] = constructor.getParameterTypes()[0];
        for (int i = 0; i < constructor.getGenericParameterTypes().length; ++i)
        {
            genericTypes[i + 1] = constructor.getGenericParameterTypes()[i];
        }
    }
    return genericTypes;
}
 
Example 5
Source Project: astrix   File: ClassConstructorFactory.java    License: Apache License 2.0 6 votes vote down vote up
public T create(Dependencies dependencies) {
	Constructor<T> factory = getFactory();
	Object[] args = new Object[factory.getParameterTypes().length];
	for (int argumentIndex = 0; argumentIndex < factory.getParameterTypes().length; argumentIndex++) {
		Class<?> argumentType = factory.getParameterTypes()[argumentIndex];
		if (argumentType.isAssignableFrom(List.class)) {
			ParameterizedType listType = (ParameterizedType) factory.getGenericParameterTypes()[argumentIndex];
			args[argumentIndex] = new ArrayList<>(dependencies.getAll(getElementType(listType)));
		} else {
			args[argumentIndex] = dependencies.get(argumentType);
		}
	}
	factory.setAccessible(true);
	T instance = newInstance(factory, args);
	runMethodInjection(instance, dependencies);
	return instance;
}
 
Example 6
Source Project: ldp4j   File: ClassDescription.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void processType(Constructor<?> type) {
	super.addTitle("Constructor");
	super.addBlockField("member", wrapElementAs(type,Member.class));
	super.addBlockField("generic declaration", wrapElementAs(type,GenericDeclaration.class));
	super.addBlockField("annotated element", wrapElementAs(type,AnnotatedElement.class));
	super.addField("accessible", type.isAccessible());
	super.addMultiField("parameter types",type.getParameterTypes());
	super.addMultiField("generic parameter types",type.getGenericParameterTypes());
	Annotation[][] parameterAnnotations = type.getParameterAnnotations();
	List<String> annots=new ArrayList<String>();
	for(Annotation[] pa:parameterAnnotations) {
		annots.add(Arrays.toString(pa));
	}
	super.addMultiField("parameter annotations",annots);
	super.addField("var args",type.isVarArgs());
	super.addMultiField("exception types",type.getExceptionTypes());
	super.addMultiField("generic exception types",type.getGenericExceptionTypes());
}
 
Example 7
public Constructor getConstructorWithNArguments(Class clazz, int n) {
    Constructor[] ctors = clazz.getDeclaredConstructors();
    Constructor ctor = null;
    for (int i = 0; i < ctors.length; i++) {
        ctor = ctors[i];
        if (ctor.getGenericParameterTypes().length == n) {
            break;
        }
    }
    return ctor;
}
 
Example 8
private static Object[] convertConstructors(Constructor[] constructors) {
    Object[] ret=new Object[constructors.length*6];
    int i=0;
    for (Constructor m : constructors) {
        Class[] parameterTypes;
        try {
            parameterTypes = m.getParameterTypes();
        }catch (Throwable e){ continue;}
        ret[i++]=m;
        ret[i++]=void.class;
        ret[i++]=null;
        ret[i++]= parameterTypes;
        Type[] genericParameterTypes = m.getGenericParameterTypes();
        for (int j=genericParameterTypes.length;j--!=0;){
            if(genericParameterTypes[j]==parameterTypes[j])
                genericParameterTypes[j]=null;
        }
        ret[i++]= genericParameterTypes;
        if(m.isVarArgs()&&parameterTypes[parameterTypes.length-1].isArray()){
            Type t=genericParameterTypes[genericParameterTypes.length-1];
            Class r=parameterTypes[parameterTypes.length-1];
            if(t==r) ret[i++]=r.getComponentType();
            else ret[i++]=((GenericArrayType)t).getGenericComponentType();
        }else ret[i++]=null;
    }
    return ret;
}
 
Example 9
public ModelClassConstructor(Constructor<ModelType> constructor, StaticInjectAnnotationProcessorFactory[] processorFactories, DefaultInjectionStrategy defaultInjectionStrategy) {
    this.constructor = constructor;
    this.hasInjectAnnotation = constructor.isAnnotationPresent(Inject.class);

    Type[] parameterTypes = constructor.getGenericParameterTypes();
    this.constructorParametersArray = new ConstructorParameter[parameterTypes.length];

    for (int i = 0; i < parameterTypes.length; i++) {
        Type genericType = ReflectionUtil.mapPrimitiveClasses(parameterTypes[i]);
        boolean isPrimitive = (parameterTypes[i] != genericType);
        this.constructorParametersArray[i] = new ConstructorParameter(
                constructor.getParameterAnnotations()[i], constructor.getParameterTypes()[i], genericType, isPrimitive, i,
                processorFactories, defaultInjectionStrategy);
    }
}
 
Example 10
Source Project: java-di   File: BeanSpecTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testTaggedAnnotation() throws Exception {
    Constructor<LeatherSmoother.Host> constructor = LeatherSmoother.Host.class.getConstructor(LeatherSmoother.class);
    Annotation[] annotations = constructor.getParameterAnnotations()[0];
    Type paramType = constructor.getGenericParameterTypes()[0];
    BeanSpec spec = BeanSpec.of(paramType, annotations, Genie.create());
    eq(1, spec.taggedAnnotations(Qualifier.class).length);
    eq(0, spec.taggedAnnotations(InjectTag.class).length);
    eq(0, spec.taggedAnnotations(Retention.class).length);
    eq(0, spec.taggedAnnotations(Target.class).length);
    eq(0, spec.taggedAnnotations(Inherited.class).length);
    eq(0, spec.taggedAnnotations(Documented.class).length);
}
 
Example 11
Source Project: flink   File: ExtractionUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Extracts ordered parameter names from a constructor that takes all of the given fields with
 * matching (possibly primitive) type and name.
 */
private static @Nullable List<String> extractConstructorParameterNames(
		Constructor<?> constructor,
		List<Field> fields) {
	final Type[] parameterTypes = constructor.getGenericParameterTypes();

	List<String> parameterNames = extractExecutableNames(constructor);
	if (parameterNames == null) {
		return null;
	}

	final Map<String, Type> fieldMap = fields.stream()
		.collect(Collectors.toMap(Field::getName, Field::getGenericType));

	// check that all fields are represented in the parameters of the constructor
	for (int i = 0; i < parameterNames.size(); i++) {
		final String parameterName = parameterNames.get(i);
		final Type fieldType = fieldMap.get(parameterName); // might be null
		final Type parameterType = parameterTypes[i];
		// we are tolerant here because frameworks such as Avro accept a boxed type even though
		// the field is primitive
		if (!primitiveToWrapper(parameterType).equals(primitiveToWrapper(fieldType))) {
			return null;
		}
	}

	return parameterNames;
}
 
Example 12
Source Project: kurento-java   File: ParamsFlattener.java    License: Apache License 2.0 5 votes vote down vote up
private Object unflattedComplexType(Class<?> clazz, Props props, ObjectRefsManager manager) {

    Constructor<?> constructor = clazz.getConstructors()[0];
    
    List<Type> constClasses = new ArrayList<>();
    Class<?>[] parameterTypes = constructor.getParameterTypes();
    Type[] parameterGenericTypes = constructor.getGenericParameterTypes();
    for (int i = 0; i < parameterGenericTypes.length; i++) {
    	if (parameterGenericTypes[i] instanceof ParameterizedTypeImpl) {
    		// This is a class with a generic type
    		// (for example, a java.util.List<java.lang.String>)
    		constClasses.add(parameterGenericTypes[i]);
    	} else {
    		constClasses.add(parameterTypes[i]);
    	}
    }
    
    Object[] constParams = new Object[parameterTypes.length];
    List<String> paramNames = ParamAnnotationUtils.getParamNames(constructor);

    for (int i = 0; i < constParams.length; i++) {
      String paramName = paramNames.get(i);
      constParams[i] = unflattenValue(paramName, constClasses.get(i), props.getProp(paramName),
          manager);
    }

    try {
      return constructor.newInstance(constParams);
    } catch (Exception e) {
      throw new ProtocolException(
          "Exception while creating an object for the class '" + clazz.getSimpleName() + "'", e);
    }
  }
 
Example 13
public LambdaExecutable(Constructor<?> constructor) {
	this.parameterTypes = constructor.getGenericParameterTypes();
	this.returnType = constructor.getDeclaringClass();
	this.name = constructor.getName();
	this.executable = constructor;
}
 
Example 14
Source Project: reef   File: JavaNodeFactory.java    License: Apache License 2.0 4 votes vote down vote up
private static <T> ConstructorDef<T> createConstructorDef(
    final boolean isClassInjectionCandidate, final Constructor<T> constructor,
    final boolean injectable) throws ClassHierarchyException {
  // We don't support injection of non-static member classes with @Inject
  // annotations.
  if (injectable && !isClassInjectionCandidate) {
    throw new ClassHierarchyException("Cannot @Inject non-static member class unless the enclosing class an @Unit. "
        + " Nested class is:"
        + ReflectionUtilities.getFullName(constructor.getDeclaringClass()));
  }
  // TODO: When we use paramTypes below, we strip generic parameters.  Is that OK?
  final Class<?>[] paramTypes = constructor.getParameterTypes();
  final Type[] genericParamTypes = constructor.getGenericParameterTypes();
  final Annotation[][] paramAnnotations = constructor.getParameterAnnotations();
  if (paramTypes.length != paramAnnotations.length) {
    throw new IllegalStateException("The paramTypes.length is " + paramTypes.length
            + ", and paramAnnotations.length is " + paramAnnotations.length
            + ". These values should be equal."
    );
  }
  final ConstructorArg[] args = new ConstructorArg[genericParamTypes.length];
  for (int i = 0; i < genericParamTypes.length; i++) {
    // If this parameter is an injection future, unwrap the target class,
    // and remember by setting isFuture to true.
    final Type type;
    final boolean isFuture;
    if (InjectionFuture.class.isAssignableFrom(paramTypes[i])) {
      type = ReflectionUtilities.getInterfaceTarget(InjectionFuture.class, genericParamTypes[i]);
      isFuture = true;
    } else {
      type = paramTypes[i];
      isFuture = false;
    }
    // Make node of the named parameter annotation (if any).
    Parameter named = null;
    for (int j = 0; j < paramAnnotations[i].length; j++) {
      final Annotation annotation = paramAnnotations[i][j];
      if (annotation instanceof Parameter) {
        if (!isClassInjectionCandidate || !injectable) {
          throw new ClassHierarchyException(constructor + " is not injectable, but it has an @Parameter annotation.");
        }
        named = (Parameter) annotation;
      }
    }
    args[i] = new ConstructorArgImpl(
        ReflectionUtilities.getFullName(type), named == null ? null
        : ReflectionUtilities.getFullName(named.value()),
        isFuture);
  }
  return new ConstructorDefImpl<T>(
      ReflectionUtilities.getFullName(constructor.getDeclaringClass()),
      args, injectable);
}
 
Example 15
Source Project: dorado   File: ReaderUtils.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Collects constructor-level parameters from class.
 *
 * @param cls     is a class for collecting
 * @param swagger is the instance of the Swagger
 * @return the collection of supported parameters
 */
public static List<Parameter> collectConstructorParameters(Class<?> cls, Swagger swagger) {
    if (cls.isLocalClass() || (cls.isMemberClass() && !Modifier.isStatic(cls.getModifiers()))) {
        return Collections.emptyList();
    }

    List<Parameter> selected = Collections.emptyList();
    int maxParamsCount = 0;

    for (Constructor<?> constructor : cls.getDeclaredConstructors()) {
        if (!ReflectionUtils.isConstructorCompatible(constructor)
                && !ReflectionUtils.isInject(Arrays.asList(constructor.getDeclaredAnnotations()))) {
            continue;
        }

        final Type[] genericParameterTypes = constructor.getGenericParameterTypes();
        final Annotation[][] annotations = constructor.getParameterAnnotations();

        int paramsCount = 0;
        final List<Parameter> parameters = new ArrayList<Parameter>();
        for (int i = 0; i < genericParameterTypes.length; i++) {
            final List<Annotation> tmpAnnotations = Arrays.asList(annotations[i]);
            if (isContext(tmpAnnotations)) {
                paramsCount++;
            } else {
                final Type genericParameterType = genericParameterTypes[i];
                final List<Parameter> tmpParameters = collectParameters(genericParameterType, tmpAnnotations);
                if (tmpParameters.size() >= 1) {
                    for (Parameter tmpParameter : tmpParameters) {
                        if (ParameterProcessor.applyAnnotations(swagger, tmpParameter, genericParameterType, tmpAnnotations) != null) {
                            parameters.add(tmpParameter);
                        }
                    }
                    paramsCount++;
                }
            }
        }

        if (paramsCount >= maxParamsCount) {
            maxParamsCount = paramsCount;
            selected = parameters;
        }
    }

    return selected;
}
 
Example 16
public ExceptionGenerator build() {
  Constructor<? extends Exception> constructor = getConstructor(exceptionType);
  Type[] parameterTypes = constructor.getGenericParameterTypes();
  Annotation[][] parametersAnnotations = constructor.getParameterAnnotations();

  Integer bodyIndex = -1;
  Integer requestIndex = -1;
  Integer headerMapIndex = -1;
  Integer numOfParams = parameterTypes.length;
  Type bodyType = null;

  for (int i = 0; i < parameterTypes.length; i++) {
    Annotation[] paramAnnotations = parametersAnnotations[i];
    boolean foundAnnotation = false;
    for (Annotation annotation : paramAnnotations) {
      if (annotation.annotationType().equals(ResponseHeaders.class)) {
        checkState(headerMapIndex == -1,
            "Cannot have two parameters tagged with @ResponseHeaders");
        checkState(Types.getRawType(parameterTypes[i]).equals(Map.class),
            "Response Header map must be of type Map, but was %s", parameterTypes[i]);
        headerMapIndex = i;
        foundAnnotation = true;
        break;
      }
    }
    if (!foundAnnotation) {
      if (parameterTypes[i].equals(Request.class)) {
        checkState(requestIndex == -1,
            "Cannot have two parameters either without annotations or with object of type feign.Request");
        requestIndex = i;
      } else {
        checkState(bodyIndex == -1,
            "Cannot have two parameters either without annotations or with @ResponseBody annotation");
        bodyIndex = i;
        bodyType = parameterTypes[i];
      }
    }
  }

  ExceptionGenerator generator = new ExceptionGenerator(
      bodyIndex,
      requestIndex,
      headerMapIndex,
      numOfParams,
      bodyType,
      exceptionType,
      responseBodyDecoder);

  validateGeneratorCanBeUsedToGenerateExceptions(generator);
  return generator;
}
 
Example 17
Source Project: Java2PlantUML   File: Parser.java    License: Apache License 2.0 4 votes vote down vote up
protected static void addConstructorUses(Set<Relation> relations, Class<?> fromType, Constructor<?> c) {
    Type[] genericParameterTypes = c.getGenericParameterTypes();
    for(int i = 0; i < genericParameterTypes.length; i++) {
        addConstructorUse(relations, fromType, genericParameterTypes[i], c);
    }
}
 
Example 18
public void testMandatoryParamsMatch() {
    // List of RPC names that don't have a constructor that has all mandatory params
    List<String> rpcsWithInvalidConstructor = new ArrayList<>();

    // List of the RPC names that couldn't be found in code
    // potentially because of a mismatch between name in the RPC spec xml file and name in code
    List<String> rpcsFromXmlNotFoundInCode = new ArrayList<>();

    // Loop through all RPCs that were loaded from RPC spec XML file
    // and make sure that every RPC has a constructor that has all mandatory params
    for (String rpcName : rpcMandatoryParamsMapFromXml.keySet()) {
        Class aClass;
        try {
            aClass = Class.forName(RPC_PACKAGE_PREFIX + rpcName);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            rpcsFromXmlNotFoundInCode.add(rpcName);
            continue;
        }
        List<String> mandatoryParamsListFromXML = new ArrayList<>();
        for (Parameter param : rpcMandatoryParamsMapFromXml.get(rpcName)) {
            String type = param.type;
            // If the param is a list of objects, the type should be like "List<Object>"
            if (param.isArray){
                type = String.format("List<%s>", type);
            }
            mandatoryParamsListFromXML.add(type);
        }
        List<String> mandatoryParamsListFromCode = new ArrayList<>();
        boolean rpcHasValidConstructor = false;
        for (Constructor constructor : aClass.getConstructors()){
            mandatoryParamsListFromCode.clear();
            for (Type paramType : constructor.getGenericParameterTypes()){
                String paramFullType = paramType.toString();
                String paramSimpleType;

                // If the param is a list of objects, the type should be like "List<Object>"
                if (paramFullType.matches("java.util.List<.+>")) {
                    paramSimpleType = String.format("List<%s>", paramFullType.substring(paramFullType.lastIndexOf('.') + 1, paramFullType.length() - 1));
                }
                // If the param is a simple object for example "java.lang.String", the type should be the last part "String"
                else if (!paramFullType.contains(">")){
                    paramSimpleType = paramFullType.substring(paramFullType.lastIndexOf('.') + 1, paramFullType.length());
                }
                else {
                    paramSimpleType = paramFullType;
                }
                mandatoryParamsListFromCode.add(paramSimpleType);
            }
            if (mandatoryParamsListFromCode.containsAll(mandatoryParamsListFromXML) && mandatoryParamsListFromXML.containsAll(mandatoryParamsListFromCode)){
                rpcHasValidConstructor = true;
                break;
            }
        }
        if (!rpcHasValidConstructor){
            rpcsWithInvalidConstructor.add(rpcName);
        }
    }
    assertTrue("The following RPCs were not found in the code: " + rpcsFromXmlNotFoundInCode, rpcsFromXmlNotFoundInCode.isEmpty());
    assertTrue("The following RPCs don't have a constructor that has all the mandatory params: " + rpcsWithInvalidConstructor, rpcsWithInvalidConstructor.isEmpty());
}
 
Example 19
@SuppressWarnings( "raw" )
private ConstructorModel newConstructorModel( Class<?> fragmentClass,
                                              Constructor<?> realConstructor,
                                              Constructor<?> injectedConstructor
)
{
    int idx = 0;
    InjectedParametersModel parameters = new InjectedParametersModel();
    Annotation[][] parameterAnnotations = injectedConstructor.getParameterAnnotations();
    for( Type type : injectedConstructor.getGenericParameterTypes() )
    {
        Annotation injectionAnnotation = Stream.of( parameterAnnotations[ idx ] )
                                               .filter( typeHasAnnotation( InjectionScope.class ) )
                                               .findFirst().orElse( null );

        if( injectionAnnotation == null )
        {
            if( fragmentClass.getSuperclass().isMemberClass() )
            {
                injectionAnnotation = new Uses()
                {
                    @Override
                    public Class<? extends Annotation> annotationType()
                    {
                        return Uses.class;
                    }
                };
            }
            else
            {
                return null; // invalid constructor parameter
            }
        }

        boolean optional = DependencyModel.isOptional( injectionAnnotation, parameterAnnotations[ idx ] );

        Type genericType = type;
        if( genericType instanceof ParameterizedType )
        {
            genericType = new ParameterizedTypeInstance( ( (ParameterizedType) genericType ).getActualTypeArguments(), ( (ParameterizedType) genericType )
                .getRawType(), ( (ParameterizedType) genericType ).getOwnerType() );

            for( int i = 0; i < ( (ParameterizedType) genericType ).getActualTypeArguments().length; i++ )
            {
                Type typeArg = ( (ParameterizedType) genericType ).getActualTypeArguments()[ i ];
                if( typeArg instanceof TypeVariable )
                {
                    typeArg = Classes.resolveTypeVariable( (TypeVariable) typeArg, realConstructor.getDeclaringClass(), fragmentClass );
                    ( (ParameterizedType) genericType ).getActualTypeArguments()[ i ] = typeArg;
                }
            }
        }

        DependencyModel dependencyModel = new DependencyModel( injectionAnnotation, genericType, fragmentClass, optional,
                                                               parameterAnnotations[ idx ] );
        parameters.addDependency( dependencyModel );
        idx++;
    }
    return new ConstructorModel( realConstructor, parameters );
}
 
Example 20
Source Project: flink   File: TypeExtractionUtils.java    License: Apache License 2.0 4 votes vote down vote up
public LambdaExecutable(Constructor<?> constructor) {
	this.parameterTypes = constructor.getGenericParameterTypes();
	this.returnType = constructor.getDeclaringClass();
	this.name = constructor.getName();
	this.executable = constructor;
}