List of usage examples for java.lang.reflect Method getTypeParameters
@Override @SuppressWarnings({ "rawtypes", "unchecked" }) public TypeVariable<Method>[] getTypeParameters()
From source file:Main.java
public static void main(String... args) { try {/*from w w w. java2s . co m*/ Class<?> c = Class.forName("Main"); Method[] allMethods = c.getDeclaredMethods(); for (Method m : allMethods) { TypeVariable[] types = m.getTypeParameters(); for (TypeVariable t : types) { System.out.println(t); } } } catch (ClassNotFoundException x) { x.printStackTrace(); } }
From source file:GenericReflectionTest.java
public static void printMethod(Method m) { String name = m.getName();// ww w . j av a2s .c om System.out.print(Modifier.toString(m.getModifiers())); System.out.print(" "); printTypes(m.getTypeParameters(), "<", ", ", "> ", true); printType(m.getGenericReturnType(), false); System.out.print(" "); System.out.print(name); System.out.print("("); printTypes(m.getGenericParameterTypes(), "", ", ", "", false); System.out.println(")"); }
From source file:com.ms.commons.test.common.ReflectUtil.java
public static Object invokeMethodByMemoryRow(Object object, Method method, MemoryRow memoryRow, Mutable outParameters) {// ww w. ja va 2s. c o m Class<?>[] parameterTypes = method.getParameterTypes(); method.getTypeParameters(); Object[] parameterObjects = new Object[parameterTypes.length]; for (int i = 0; i < parameterTypes.length; i++) { Class<?> clazz = parameterTypes[i]; MemoryField field = memoryRow.getField(i + 1); Object value = (field.getType() == MemoryFieldType.Null) ? null : field.getValue(); parameterObjects[i] = TypeConvertUtil.convert(clazz, value); } if (outParameters != null) { outParameters.setValue(Arrays.asList(parameterObjects)); } try { method.setAccessible(true); return method.invoke(object, parameterObjects); } catch (Exception e) { throw ExceptionUtil.wrapToRuntimeException(e); } }
From source file:Main.java
public static void dumpMethod(final Method method) { final StringBuilder builder = new StringBuilder(); builder.append("------------------------------\n"); builder.append("MethodName: ").append(method.getName()).append("\n"); builder.append("ParameterTypes:{"); for (Class<?> cls : method.getParameterTypes()) { builder.append(cls.getName()).append(", "); }/*from w w w. j a v a 2 s .com*/ builder.append("}\n"); builder.append("GenericParameterTypes:{"); for (Type cls : method.getGenericParameterTypes()) { builder.append(cls.getClass()).append(", "); } builder.append("}\n"); builder.append("TypeParameters:{"); for (TypeVariable<Method> cls : method.getTypeParameters()) { builder.append(cls.getName()).append(", "); } builder.append("}\n"); builder.append("DeclaredAnnotations:{"); for (Annotation cls : method.getDeclaredAnnotations()) { builder.append(cls).append(", "); } builder.append("}\n"); builder.append("Annotations:{"); for (Annotation cls : method.getAnnotations()) { builder.append(cls).append(", "); } builder.append("}\n"); builder.append("ExceptionTypes:{"); for (Class<?> cls : method.getExceptionTypes()) { builder.append(cls.getName()).append(", "); ; } builder.append("}\n"); builder.append("ReturnType: ").append(method.getReturnType()); builder.append("\nGenericReturnType: ").append(method.getGenericReturnType()); builder.append("\nDeclaringClass: ").append(method.getDeclaringClass()); builder.append("\n"); System.out.println(builder.toString()); }
From source file:net.jodah.typetools.TypeResolver.java
/** * Populates the {@code map} with variable/argument pairs for the {@code functionalInterface}. *///from w ww. j ava2 s .co m private static void populateLambdaArgs(Class<?> functionalInterface, final Class<?> lambdaType, Map<TypeVariable<?>, Type> map) { if (GET_CONSTANT_POOL != null) { try { // Find SAM for (Method m : functionalInterface.getMethods()) { if (!m.isDefault() && !Modifier.isStatic(m.getModifiers()) && !m.isBridge()) { // Skip methods that override Object.class Method objectMethod = OBJECT_METHODS.get(m.getName()); if (objectMethod != null && Arrays.equals(m.getTypeParameters(), objectMethod.getTypeParameters())) continue; // Get functional interface's type params Type returnTypeVar = m.getGenericReturnType(); Type[] paramTypeVars = m.getGenericParameterTypes(); // Get lambda's type arguments ConstantPool constantPool = (ConstantPool) GET_CONSTANT_POOL.invoke(lambdaType); String[] methodRefInfo = constantPool.getMemberRefInfoAt( constantPool.getSize() - resolveMethodRefOffset(constantPool, lambdaType)); // Skip auto boxing methods if (methodRefInfo[1].equals("valueOf") && constantPool.getSize() > 22) { try { methodRefInfo = constantPool.getMemberRefInfoAt(constantPool.getSize() - resolveAutoboxedMethodRefOffset(constantPool, lambdaType)); } catch (MethodRefOffsetResolutionFailed ignore) { } } if (returnTypeVar instanceof TypeVariable) { Class<?> returnType = TypeDescriptor.getReturnType(methodRefInfo[2]) .getType(lambdaType.getClassLoader()); if (!returnType.equals(Void.class)) map.put((TypeVariable<?>) returnTypeVar, returnType); } TypeDescriptor[] arguments = TypeDescriptor.getArgumentTypes(methodRefInfo[2]); // Handle arbitrary object instance method references int paramOffset = 0; if (paramTypeVars[0] instanceof TypeVariable && paramTypeVars.length == arguments.length + 1) { Class<?> instanceType = TypeDescriptor.getObjectType(methodRefInfo[0]) .getType(lambdaType.getClassLoader()); map.put((TypeVariable<?>) paramTypeVars[0], instanceType); paramOffset = 1; } // Handle local final variables from context that are passed as arguments. int argOffset = 0; if (paramTypeVars.length < arguments.length) { argOffset = arguments.length - paramTypeVars.length; } for (int i = 0; i + argOffset < arguments.length; i++) { if (paramTypeVars[i] instanceof TypeVariable) { map.put((TypeVariable<?>) paramTypeVars[i + paramOffset], arguments[i + argOffset].getType(lambdaType.getClassLoader())); } } break; } } } catch (Exception ignore) { } } }
From source file:org.springframework.core.GenericTypeResolver.java
/** * Determine the target type for the generic return type of the given * <em>generic method</em>, where formal type variables are declared on * the given method itself./*from w w w . java 2 s . c o m*/ * * <p>For example, given a factory method with the following signature, * if {@code resolveReturnTypeForGenericMethod()} is invoked with the reflected * method for {@code creatProxy()} and an {@code Object[]} array containing * {@code MyService.class}, {@code resolveReturnTypeForGenericMethod()} will * infer that the target return type is {@code MyService}. * * <pre>{@code public static <T> T createProxy(Class<T> clazz)}</pre> * * <h4>Possible Return Values</h4> * <ul> * <li>the target return type, if it can be inferred</li> * <li>the {@linkplain Method#getReturnType() standard return type}, if * the given {@code method} does not declare any {@linkplain * Method#getTypeParameters() formal type variables}</li> * <li>the {@linkplain Method#getReturnType() standard return type}, if the * target return type cannot be inferred (e.g., due to type erasure)</li> * <li>{@code null}, if the length of the given arguments array is shorter * than the length of the {@linkplain * Method#getGenericParameterTypes() formal argument list} for the given * method</li> * </ul> * * @param method the method to introspect, never {@code null} * @param args the arguments that will be supplied to the method when it is * invoked, never {@code null} * @return the resolved target return type, the standard return type, or * {@code null} * @since 3.2 * @see #resolveReturnType */ public static Class<?> resolveReturnTypeForGenericMethod(Method method, Object[] args) { Assert.notNull(method, "method must not be null"); Assert.notNull(args, "args must not be null"); if (logger.isDebugEnabled()) { logger.debug(String.format("Resolving return type for [%s] with concrete method arguments [%s].", method.toGenericString(), ObjectUtils.nullSafeToString(args))); } final TypeVariable<Method>[] declaredTypeVariables = method.getTypeParameters(); final Type genericReturnType = method.getGenericReturnType(); final Type[] methodArgumentTypes = method.getGenericParameterTypes(); // No declared type variables to inspect, so just return the standard return type. if (declaredTypeVariables.length == 0) { return method.getReturnType(); } // The supplied argument list is too short for the method's signature, so // return null, since such a method invocation would fail. if (args.length < methodArgumentTypes.length) { return null; } // Ensure that the type variable (e.g., T) is declared directly on the method // itself (e.g., via <T>), not on the enclosing class or interface. boolean locallyDeclaredTypeVariableMatchesReturnType = false; for (TypeVariable<Method> currentTypeVariable : declaredTypeVariables) { if (currentTypeVariable.equals(genericReturnType)) { if (logger.isDebugEnabled()) { logger.debug(String.format( "Found declared type variable [%s] that matches the target return type [%s].", currentTypeVariable, genericReturnType)); } locallyDeclaredTypeVariableMatchesReturnType = true; break; } } if (locallyDeclaredTypeVariableMatchesReturnType) { for (int i = 0; i < methodArgumentTypes.length; i++) { final Type currentMethodArgumentType = methodArgumentTypes[i]; if (currentMethodArgumentType.equals(genericReturnType)) { if (logger.isDebugEnabled()) { logger.debug(String.format( "Found method argument type at index [%s] that matches the target return type.", i)); } return args[i].getClass(); } if (currentMethodArgumentType instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) currentMethodArgumentType; Type[] actualTypeArguments = parameterizedType.getActualTypeArguments(); for (int j = 0; j < actualTypeArguments.length; j++) { final Type typeArg = actualTypeArguments[j]; if (typeArg.equals(genericReturnType)) { if (logger.isDebugEnabled()) { logger.debug(String.format( "Found method argument type at index [%s] that is parameterized with a type argument that matches the target return type.", i)); } if (args[i] instanceof Class) { return (Class<?>) args[i]; } else { // Consider adding logic to determine the class of the // J'th typeArg, if possible. logger.info(String.format( "Could not determine the target type for type argument [%s] for method [%s].", typeArg, method.toGenericString())); // For now, just fall back... return method.getReturnType(); } } } } } } // Fall back... return method.getReturnType(); }
From source file:org.semispace.SemiSpace.java
/** * Protected for the benefit of junit test(s) * //from w w w . j a v a2s . co m * @param examine Non-null object * / protected Map<String, Object> retrievePropertiesFromObject(ISemiSpaceTuple examine) { Map<String, Object> map = examine.getSearchMap(); fillMapWithPublicFields(examine); addGettersToMap(examine, map); // if ( examine instanceof InternalQuery ) { // map.put(SemiSpace.ADMIN_GROUP_IS_FLAGGED, "true"); // } // Need to rename class entry in order to separate on class elements. String tag = (String)map.remove("tag"); //TODO ???? map.put("tag", tag ); return map; } /** * Add an objects getter names and values in a map. Note that all values are converted to strings. */ private void addGettersToMap(ISemiSpaceTuple examine, Map<String, Object> map) { final Set<String> getters = new HashSet<String>(); final Method[] methods = examine.getClass().getMethods(); final Map<String, Method> keyedMethod = new HashMap<String, Method>(); final Map<String, String> keyedMethodName = new HashMap<String, String>(); for (Method method : methods) { final String name = method.getName(); final int parameterLength = method.getTypeParameters().length; if (parameterLength == 0 && name.startsWith("get")) { // Equalize key to [get][set][X]xx String normalized = name.substring(3, 4).toLowerCase() + name.substring(4); getters.add(normalized); keyedMethod.put(name, method); keyedMethodName.put(normalized, name); //log.info("Got name "+name+" which was normalized to "+normalized); } } for (String name : getters) { try { Object value = keyedMethod.get(keyedMethodName.get(name)).invoke(examine, null); //log.info(">> want to insert "+name+"="+value); if (value != null) { map.put(name, "" + value); } } catch (IllegalAccessException e) { log.logError("Could not access method g" + name + ". Got (masked exception) " + e.getMessage(), e); } catch (InvocationTargetException e) { log.logError("Could not access method g" + name + ". Got (masked exception) " + e.getMessage(), e); } } }
From source file:org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.java
/** * Determine the target type for the given bean definition which is based on * a factory method. Only called if there is no singleton instance registered * for the target bean already.// w ww . j av a 2 s. c o m * <p>This implementation determines the type matching {@link #createBean}'s * different creation strategies. As far as possible, we'll perform static * type checking to avoid creation of the target bean. * @param beanName the name of the bean (for error handling purposes) * @param mbd the merged bean definition for the bean * @param typesToMatch the types to match in case of internal type matching purposes * (also signals that the returned {@code Class} will never be exposed to application code) * @return the type for the bean if determinable, or {@code null} otherwise * @see #createBean */ @Nullable protected Class<?> getTypeForFactoryMethod(String beanName, RootBeanDefinition mbd, Class<?>... typesToMatch) { ResolvableType cachedReturnType = mbd.factoryMethodReturnType; if (cachedReturnType != null) { return cachedReturnType.resolve(); } Class<?> factoryClass; boolean isStatic = true; String factoryBeanName = mbd.getFactoryBeanName(); if (factoryBeanName != null) { if (factoryBeanName.equals(beanName)) { throw new BeanDefinitionStoreException(mbd.getResourceDescription(), beanName, "factory-bean reference points back to the same bean definition"); } // Check declared factory method return type on factory class. factoryClass = getType(factoryBeanName); isStatic = false; } else { // Check declared factory method return type on bean class. factoryClass = resolveBeanClass(mbd, beanName, typesToMatch); } if (factoryClass == null) { return null; } factoryClass = ClassUtils.getUserClass(factoryClass); // If all factory methods have the same return type, return that type. // Can't clearly figure out exact method due to type converting / autowiring! Class<?> commonType = null; Method uniqueCandidate = null; int minNrOfArgs = (mbd.hasConstructorArgumentValues() ? mbd.getConstructorArgumentValues().getArgumentCount() : 0); Method[] candidates = this.factoryMethodCandidateCache.computeIfAbsent(factoryClass, ReflectionUtils::getUniqueDeclaredMethods); for (Method candidate : candidates) { if (Modifier.isStatic(candidate.getModifiers()) == isStatic && mbd.isFactoryMethod(candidate) && candidate.getParameterCount() >= minNrOfArgs) { // Declared type variables to inspect? if (candidate.getTypeParameters().length > 0) { try { // Fully resolve parameter names and argument values. Class<?>[] paramTypes = candidate.getParameterTypes(); String[] paramNames = null; ParameterNameDiscoverer pnd = getParameterNameDiscoverer(); if (pnd != null) { paramNames = pnd.getParameterNames(candidate); } ConstructorArgumentValues cav = mbd.getConstructorArgumentValues(); Set<ConstructorArgumentValues.ValueHolder> usedValueHolders = new HashSet<>( paramTypes.length); Object[] args = new Object[paramTypes.length]; for (int i = 0; i < args.length; i++) { ConstructorArgumentValues.ValueHolder valueHolder = cav.getArgumentValue(i, paramTypes[i], (paramNames != null ? paramNames[i] : null), usedValueHolders); if (valueHolder == null) { valueHolder = cav.getGenericArgumentValue(null, null, usedValueHolders); } if (valueHolder != null) { args[i] = valueHolder.getValue(); usedValueHolders.add(valueHolder); } } Class<?> returnType = AutowireUtils.resolveReturnTypeForFactoryMethod(candidate, args, getBeanClassLoader()); uniqueCandidate = (commonType == null && returnType == candidate.getReturnType() ? candidate : null); commonType = ClassUtils.determineCommonAncestor(returnType, commonType); if (commonType == null) { // Ambiguous return types found: return null to indicate "not determinable". return null; } } catch (Throwable ex) { if (logger.isDebugEnabled()) { logger.debug("Failed to resolve generic return type for factory method: " + ex); } } } else { uniqueCandidate = (commonType == null ? candidate : null); commonType = ClassUtils.determineCommonAncestor(candidate.getReturnType(), commonType); if (commonType == null) { // Ambiguous return types found: return null to indicate "not determinable". return null; } } } } if (commonType == null) { return null; } // Common return type found: all factory methods return same type. For a non-parameterized // unique candidate, cache the full type declaration context of the target factory method. cachedReturnType = (uniqueCandidate != null ? ResolvableType.forMethodReturnType(uniqueCandidate) : ResolvableType.forClass(commonType)); mbd.factoryMethodReturnType = cachedReturnType; return cachedReturnType.resolve(); }
From source file:org.evosuite.setup.TestClusterGenerator.java
private boolean addDependencyClass(GenericClass clazz, int recursionLevel) { if (recursionLevel > Properties.CLUSTER_RECURSION) { logger.debug("Maximum recursion level reached, not adding dependency {}", clazz.getClassName()); return false; }/* w ww. j av a2 s . co m*/ clazz = clazz.getRawGenericClass(); if (analyzedClasses.contains(clazz.getRawClass())) { return true; } analyzedClasses.add(clazz.getRawClass()); // We keep track of generic containers in case we find other concrete generic components during runtime if (clazz.isAssignableTo(Collection.class) || clazz.isAssignableTo(Map.class)) { if (clazz.getNumParameters() > 0) { containerClasses.add(clazz.getRawClass()); } } if (clazz.equals(String.class)) { return false; } try { TestCluster cluster = TestCluster.getInstance(); logger.debug("Adding dependency class {}", clazz.getClassName()); // TODO: Should we include declared classes as well? if (!canUse(clazz.getRawClass())) { logger.info("*** Cannot use class: {}", clazz.getClassName()); return false; } // Add all constructors for (Constructor<?> constructor : getConstructors(clazz.getRawClass())) { String name = "<init>" + org.objectweb.asm.Type.getConstructorDescriptor(constructor); if (Properties.TT) { String orig = name; name = BooleanTestabilityTransformation.getOriginalNameDesc(clazz.getClassName(), "<init>", org.objectweb.asm.Type.getConstructorDescriptor(constructor)); if (!orig.equals(name)) logger.info("TT name: {} -> {}", orig, name); } if (canUse(constructor)) { GenericConstructor genericConstructor = new GenericConstructor(constructor, clazz); try { cluster.addGenerator(clazz.getWithWildcardTypes(), genericConstructor); addDependencies(genericConstructor, recursionLevel + 1); logger.debug("Keeping track of {}.{}{}", constructor.getDeclaringClass().getName(), constructor.getName(), Type.getConstructorDescriptor(constructor)); } catch (Throwable t) { logger.info("Error adding constructor {}: {}", constructor.getName(), t.getMessage()); } } else { logger.debug("Constructor cannot be used: {}", constructor); } } // Add all methods for (Method method : getMethods(clazz.getRawClass())) { String name = method.getName() + org.objectweb.asm.Type.getMethodDescriptor(method); if (Properties.TT) { String orig = name; name = BooleanTestabilityTransformation.getOriginalNameDesc(clazz.getClassName(), method.getName(), org.objectweb.asm.Type.getMethodDescriptor(method)); if (!orig.equals(name)) logger.info("TT name: {} -> {}", orig, name); } if (canUse(method, clazz.getRawClass()) && !method.getName().equals("hashCode")) { logger.debug("Adding method {}.{}{}", clazz.getClassName(), method.getName(), Type.getMethodDescriptor(method)); if (method.getTypeParameters().length > 0) { logger.info("Type parameters in methods are not handled yet, skipping {}", method); continue; } GenericMethod genericMethod = new GenericMethod(method, clazz); try { addDependencies(genericMethod, recursionLevel + 1); cluster.addModifier(clazz.getWithWildcardTypes(), genericMethod); // GenericClass retClass = new GenericClass( // genericMethod.getReturnType(), method.getReturnType()); GenericClass retClass = new GenericClass(method.getReturnType()); if (!retClass.isPrimitive() && !retClass.isVoid() && !retClass.isObject()) { cluster.addGenerator(retClass.getWithWildcardTypes(), genericMethod); } } catch (Throwable t) { logger.info("Error adding method {}: {}", method.getName(), t.getMessage()); } } else { logger.debug("Method cannot be used: {}", method); } } // Add all fields for (Field field : getFields(clazz.getRawClass())) { logger.debug("Checking field {}", field); if (canUse(field, clazz.getRawClass())) { logger.debug("Adding field {} for class {}", field, clazz); try { GenericField genericField = new GenericField(field, clazz); cluster.addGenerator(new GenericClass(field.getGenericType()).getWithWildcardTypes(), genericField); if (!Modifier.isFinal(field.getModifiers())) { cluster.addModifier(clazz.getWithWildcardTypes(), genericField); addDependencies(genericField, recursionLevel + 1); } } catch (Throwable t) { logger.info("Error adding field {}: {}", field.getName(), t.getMessage()); } } else { logger.debug("Field cannot be used: {}", field); } } logger.info("Finished analyzing {} at recursion level {}", clazz.getTypeName(), recursionLevel); cluster.getAnalyzedClasses().add(clazz.getRawClass()); } catch (Throwable t) { /* * NOTE: this is a problem we know it can happen in some cases in SF110, but don't * have a real solution now. As it is bound to happen, we try to minimize the logging (eg no * stack trace), although we still need to log it */ logger.error("Problem for {}. Failed to add dependencies for class {}: {}\n{}", Properties.TARGET_CLASS, clazz.getClassName(), t, Arrays.asList(t.getStackTrace())); return false; } return true; }