Example usage for java.lang.reflect Method getGenericParameterTypes

List of usage examples for java.lang.reflect Method getGenericParameterTypes

Introduction

In this page you can find the example usage for java.lang.reflect Method getGenericParameterTypes.

Prototype

@Override
public Type[] getGenericParameterTypes() 

Source Link

Usage

From source file:org.apache.axis2.transport.testkit.tests.TestResource.java

public void resolve(TestResourceSet resourceSet) {
    if (status != Status.UNRESOLVED) {
        return;/*from w  ww .j  a v  a  2 s  . c  o  m*/
    }
    for (Class<?> clazz = target.getClass(); !clazz.equals(Object.class); clazz = clazz.getSuperclass()) {
        for (Method method : clazz.getDeclaredMethods()) {
            if (method.getAnnotation(Setup.class) != null) {
                Type[] parameterTypes = method.getGenericParameterTypes();
                Object[] args = new Object[parameterTypes.length];
                for (int i = 0; i < parameterTypes.length; i++) {
                    Type parameterType = parameterTypes[i];
                    if (!(parameterType instanceof Class)) {
                        throw new Error("Generic parameters not supported in " + method);
                    }
                    Class<?> parameterClass = (Class<?>) parameterType;
                    if (parameterClass.isArray()) {
                        Class<?> componentType = parameterClass.getComponentType();
                        TestResource[] resources = resourceSet.findResources(componentType, true);
                        Object[] arg = (Object[]) Array.newInstance(componentType, resources.length);
                        for (int j = 0; j < resources.length; j++) {
                            TestResource resource = resources[j];
                            directDependencies.add(resource);
                            arg[j] = resource.getInstance();
                        }
                        args[i] = arg;
                    } else {
                        TestResource[] resources = resourceSet.findResources(parameterClass, true);
                        if (resources.length == 0) {
                            throw new Error(target.getClass().getName() + " depends on "
                                    + parameterClass.getName() + ", but none found");
                        } else if (resources.length > 1) {
                            throw new Error(target.getClass().getName() + " depends on "
                                    + parameterClass.getName() + ", but multiple candidates found");

                        }
                        TestResource resource = resources[0];
                        directDependencies.add(resource);
                        args[i] = resource.getInstance();
                    }
                }
                method.setAccessible(true);
                initializers.addFirst(new MethodInvocation(method, args));
            } else if (method.getAnnotation(TearDown.class) != null && method.getParameterTypes().length == 0) {
                method.setAccessible(true);
                finalizers.add(new MethodInvocation(method, null));
            }
        }
        for (Field field : clazz.getDeclaredFields()) {
            if (field.getAnnotation(Transient.class) != null) {
                field.setAccessible(true);
                finalizers.add(new FieldResetter(field));
            }
        }
    }
    status = Status.RESOLVED;
}

From source file:org.gradle.model.internal.manage.schema.extraction.ModelSchemaExtractor.java

private <T> void validateSetter(Class<?> type, ModelType<T> propertyType, Method setter) {
    if (!setter.getReturnType().equals(void.class)) {
        throw invalidMethod(type, setter.getName(), "setter method must have void return type");
    }//from   w w w .  jav a2  s. c  o m

    Type[] setterParameterTypes = setter.getGenericParameterTypes();
    if (setterParameterTypes.length != 1) {
        throw invalidMethod(type, setter.getName(), "setter method must have exactly one parameter");
    }

    ModelType<?> setterType = ModelType.of(setterParameterTypes[0]);
    if (!setterType.equals(propertyType)) {
        throw invalidMethod(type, setter.getName(),
                "setter method param must be of exactly the same type as the getter returns (expected: "
                        + propertyType + ", found: " + setterType + ")");
    }
}

From source file:com.startechup.tools.ModelParser.java

/**
 * Invokes the setter method that was link to the json key.
 *
 * @param method The setter method to be invoked.
 * @param classInstance The instance of the container class.
 * @param key The json key serving as the reference of the value in the json object
 * @param jsonObject The API response object.
 *///from   w w w. j a  v  a2  s.  c  o  m
private static void initMethodInvocation(Method method, Object classInstance, String key,
        JSONObject jsonObject) {
    Object value = getValueFromJsonObject(jsonObject, key, method.getName());

    // Only invoke the method when the value is not null
    if (value != null) {
        method.setAccessible(true);
        Object castedObject = value;

        if (value instanceof Number) {
            castedObject = castNumberObject(method.getParameterTypes()[0], value);
        } else if (value instanceof JSONArray) {
            if (method.getParameterTypes()[0].isArray()) {
                //TODO find a way to genetically convert json array to array, for now throw our custom exception
                throwException("Cannot parse " + JSONArray.class + " to " + method.getParameterTypes()[0]);
            } else {
                Object parameterInstance = getNewInstance(method.getParameterTypes()[0]);
                if (parameterInstance instanceof Collection) {
                    ParameterizedType parameterizedType = (ParameterizedType) method
                            .getGenericParameterTypes()[0];
                    Class<?> classType = (Class<?>) parameterizedType.getActualTypeArguments()[0];
                    castedObject = parse(classType, (JSONArray) value);
                } else {
                    //TODO find a way to genetically convert json array to the other parameter class, for now throw our custom exception
                    throwException("Cannot parse " + JSONArray.class + " to " + method.getParameterTypes()[0]);
                }
            }
        } else if (value instanceof JSONObject) {
            castedObject = parse(method.getParameterTypes()[0], ((JSONObject) value));
        }

        // Finally invoke the method after casting the values into the method parameter type
        invoke(method, classInstance, castedObject);
    }
}

From source file:org.lunarray.model.descriptor.builder.annotation.resolver.parameter.def.DefaultParameterResolverStrategy.java

/**
 * Process parameter./*from w  ww. j a  va2 s.  c  o  m*/
 * 
 * @param index
 *            The parameter index.
 * @param type
 *            The parameter type.
 * @param primary
 *            The primary declaring method.
 * @param operation
 *            The operation.
 * @return The described parameter.
 * @param <P>
 *            The parameter type.
 */
private <P> DescribedParameter<P> process(final int index, final Class<P> type, final Method primary,
        final DescribedOperation operation) {
    final ParameterBuilder<P> builder = DescribedParameter.createBuilder();
    // Base attributes.
    builder.index(index).parameterType(type).entityType(primary.getDeclaringClass());
    // Generic type.
    builder.genericType(primary.getGenericParameterTypes()[index]).operation(operation);
    // Process annotations.
    for (final Annotation annotation : primary.getParameterAnnotations()[index]) {
        builder.addAnnotation(annotation);
    }
    for (final Method m : operation.getMatches()) {
        for (final Annotation annotation : m.getParameterAnnotations()[index]) {
            builder.addAnnotation(annotation);
        }
    }
    return builder.buildDescribed();
}

From source file:com.google.code.pathlet.web.ognl.impl.InstantiatingNullHandler.java

/**
 * Returns the class for the given field via generic type check.
 *
 * @param parentClass the Class which contains as a property the Map or Collection we are finding the key for.
 * @param property    the property of the Map or Collection for the given parent class
 * @param element     <tt>true</tt> for indexed types and Maps.
 * @return Class of the specified field.
 *///from   w  w  w.j a v  a 2 s. c  o m
private Class getClass(Class parentClass, String property, boolean element) {

    try {

        Field field = reflectionProvider.getField(parentClass, property);

        Type genericType = null;

        // Check fields first
        if (field != null) {
            genericType = field.getGenericType();
        }

        // Try to get ParameterType from setter method
        if (genericType == null || !(genericType instanceof ParameterizedType)) {
            try {
                Method setter = reflectionProvider.getSetMethod(parentClass, property);
                genericType = setter.getGenericParameterTypes()[0];
            } catch (ReflectionException ognle) {
                ; // ignore
            } catch (IntrospectionException ie) {
                ; // ignore
            }
        }

        // Try to get ReturnType from getter method
        if (genericType == null || !(genericType instanceof ParameterizedType)) {
            try {
                Method getter = reflectionProvider.getGetMethod(parentClass, property);
                genericType = getter.getGenericReturnType();
            } catch (ReflectionException ognle) {
                ; // ignore
            } catch (IntrospectionException ie) {
                ; // ignore
            }
        }

        if (genericType instanceof ParameterizedType) {

            ParameterizedType type = (ParameterizedType) genericType;

            int index = (element && type.getRawType().toString().contains(Map.class.getName())) ? 1 : 0;

            Type resultType = type.getActualTypeArguments()[index];

            if (resultType instanceof ParameterizedType) {
                return (Class) ((ParameterizedType) resultType).getRawType();
            }
            return (Class) resultType;

        }
    } catch (Exception e) {
        throw new ConvertException(e);
    }
    return null;
}

From source file:org.gradle.model.internal.manage.schema.store.ModelSchemaExtractor.java

private <T> void validateSetter(ModelType<?> type, ModelType<T> propertyType, Method setter) {
    if (!setter.getReturnType().equals(void.class)) {
        throw invalidMethod(type, setter.getName(), "setter method must have void return type");
    }/*from   w  w  w  .j a  v  a  2 s  .  c  o m*/

    Type[] setterParameterTypes = setter.getGenericParameterTypes();
    if (setterParameterTypes.length != 1) {
        throw invalidMethod(type, setter.getName(), "setter method must have exactly one parameter");
    }

    ModelType<?> setterType = ModelType.of(setterParameterTypes[0]);
    if (!setterType.equals(propertyType)) {
        throw invalidMethod(type, setter.getName(),
                "setter method param must be of exactly the same type as the getter returns (expected: "
                        + propertyType + ", found: " + setterType + ")");
    }
}

From source file:com.opensymphony.xwork2.conversion.impl.DefaultObjectTypeDeterminer.java

/**
 * Returns the class for the given field via generic type check.
 *
 * @param parentClass the Class which contains as a property the Map or Collection we are finding the key for.
 * @param property    the property of the Map or Collection for the given parent class
 * @param element     <tt>true</tt> for indexed types and Maps.
 * @return Class of the specified field.
 *///  w ww  .  ja  va 2 s .co  m
private Class getClass(Class parentClass, String property, boolean element) {
    try {
        Field field = reflectionProvider.getField(parentClass, property);
        Type genericType = null;
        // Check fields first
        if (field != null) {
            genericType = field.getGenericType();
        }
        // Try to get ParameterType from setter method
        if (genericType == null || !(genericType instanceof ParameterizedType)) {
            try {
                Method setter = reflectionProvider.getSetMethod(parentClass, property);
                genericType = setter != null ? setter.getGenericParameterTypes()[0] : null;
            } catch (ReflectionException | IntrospectionException e) {
                // ignore
            }
        }

        // Try to get ReturnType from getter method
        if (genericType == null || !(genericType instanceof ParameterizedType)) {
            try {
                Method getter = reflectionProvider.getGetMethod(parentClass, property);
                genericType = getter.getGenericReturnType();
            } catch (ReflectionException | IntrospectionException e) {
                // ignore
            }
        }

        if (genericType instanceof ParameterizedType) {
            ParameterizedType type = (ParameterizedType) genericType;
            int index = (element && type.getRawType().toString().contains(Map.class.getName())) ? 1 : 0;
            Type resultType = type.getActualTypeArguments()[index];
            if (resultType instanceof ParameterizedType) {
                return (Class) ((ParameterizedType) resultType).getRawType();
            }
            return (Class) resultType;
        }
    } catch (Exception e) {
        LOG.debug("Error while retrieving generic property class for property: {}", property, e);
    }
    return null;
}

From source file:org.gradle.model.internal.method.WeaklyTypeReferencingMethod.java

public WeaklyTypeReferencingMethod(ModelType<T> target, ModelType<R> returnType, Method method) {
    this.target = target;
    this.returnType = returnType;
    this.declaringType = ModelType.of(method.getDeclaringClass());
    this.name = method.getName();
    paramTypes = ImmutableList.copyOf(Iterables.transform(Arrays.asList(method.getGenericParameterTypes()),
            new Function<Type, ModelType<?>>() {
                public ModelType<?> apply(Type type) {
                    return ModelType.of(type);
                }//from w  ww . j ava2s .  c  o  m
            }));
    modifiers = method.getModifiers();
}

From source file:org.netxilia.spi.impl.formula.function.MethodWrapper.java

public MethodWrapper(Object instance, Method method) {
    this.instance = instance;
    this.method = method;
    Class<?>[] paramTypes = method.getParameterTypes();
    paramConverters = new IParamConverter[paramTypes.length];

    Type[] genericParameterTypes = method.getGenericParameterTypes();

    for (int i = 0; i < genericParameterTypes.length; ++i) {
        Type genericParameterType = genericParameterTypes[i];
        if (genericParameterType instanceof ParameterizedType) {
            ParameterizedType aType = (ParameterizedType) genericParameterType;

            if (Iterator.class.isAssignableFrom((Class<?>) aType.getRawType())) {
                Class<?> componentType = (Class<?>) aType.getActualTypeArguments()[0];
                paramConverters[i] = new IteratorConverter(componentType);
            }//from w ww .  j  a va2s  .c  o m
        } else {
            Class<?> paramType = (Class<?>) genericParameterType;
            if (IGenericValue.class == paramType) {
                paramConverters[i] = new LazyParamConverter();
            } else if (RichValue.class == paramType) {
                paramConverters[i] = new RichValueParamConverter();
            } else {
                paramConverters[i] = new BasicTypeConverter(paramType);
            }
        }
    }

    Function annotation = this.method.getAnnotation(Function.class);
    cacheable = annotation == null || annotation.cacheable();
}

From source file:org.openengsb.core.ekb.common.EDBConverter.java

/**
 * Loads the generic parameter classes up to the given depth (1 for lists, 2 for maps)
 *///  w  w w . j ava 2  s.  c om
private List<Class<?>> getGenericParameterClasses(Method setterMethod, int depth) {
    Type t = setterMethod.getGenericParameterTypes()[0];
    ParameterizedType pType = (ParameterizedType) t;
    List<Class<?>> classes = new ArrayList<Class<?>>();
    for (int i = 0; i < depth; i++) {
        classes.add((Class<?>) pType.getActualTypeArguments()[i]);
    }
    return classes;
}