List of usage examples for java.lang.reflect Method getGenericParameterTypes
@Override
public Type[] getGenericParameterTypes()
From source file:org.gradle.internal.reflect.MethodSignatureEquivalence.java
@Override protected boolean doEquivalent(Method a, Method b) { boolean equals = new EqualsBuilder().append(a.getName(), b.getName()) .append(a.getGenericParameterTypes(), b.getGenericParameterTypes()).isEquals(); if (equals) { equals = a.getReturnType().equals(b.getReturnType()) || a.getReturnType().isAssignableFrom(b.getReturnType()) || b.getReturnType().isAssignableFrom(a.getReturnType()); }/*from ww w. j av a2 s . c om*/ return equals; }
From source file:org.lunarray.model.descriptor.builder.annotation.resolver.matchers.MutatorMatcher.java
/** * Has a generic parameter./*from w w w . j av a 2 s .c om*/ * * @param memberType * The member. * @return True if there is a generic parameter. */ private boolean matchGenericConditions(final Method memberType) { Validate.notNull(memberType, MutatorMatcher.METHOD_NULL); return memberType.getGenericParameterTypes().length == 1; }
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 ww . j a v a 2s . 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.callimachusproject.rewrite.RedirectAdviceFactory.java
FluidType[] getBindingTypes(Method method, String[] bindingNames) { Type[] types = method.getGenericParameterTypes(); Annotation[][] anns = method.getParameterAnnotations(); FluidType[] bindingTypes = new FluidType[anns.length]; loop: for (int i = 0; i < bindingTypes.length; i++) { if (bindingNames[i] == null) continue; for (Annotation ann : anns[i]) { if (type.class.equals(ann.annotationType())) { bindingTypes[i] = new FluidType(types[i], ((type) ann).value()); continue loop; }/*w w w .j a v a 2 s .c o m*/ } bindingTypes[i] = new FluidType(types[i]); } return bindingTypes; }
From source file:net.jodah.typetools.TypeResolver.java
/** * Populates the {@code map} with variable/argument pairs for the {@code functionalInterface}. *//*from www . ja v a 2 s. c o 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:therian.cdi.internal.MapperHandler.java
public MapperHandler(final AnnotatedType<?> type) { // just for error handling of(type.getMethods().stream()/*from w w w . j a va 2s. co m*/ .filter(m -> m.isAnnotationPresent(PropertyCopier.Mapping.class) && (m.getParameters().size() != 1 || m.getJavaMember().getReturnType() == void.class)) .collect(toList())).filter(l -> !l.isEmpty()).ifPresent(l -> { throw new IllegalArgumentException( "@Mapping only supports one parameter and not void signatures"); }); // TODO: use a single Therian instance if there are not redundant conversions specified by interface methods this.mapping = type.getMethods().stream().filter(m -> m.isAnnotationPresent(PropertyCopier.Mapping.class)) .collect(toMap(AnnotatedMethod::getJavaMember, am -> { final Method member = am.getJavaMember(); final Typed<Object> source = TypeUtils.wrap(member.getGenericParameterTypes()[0]); final Typed<Object> target = TypeUtils.wrap(member.getGenericReturnType()); final Therian therian = Therian.standard() .withAdditionalModules(TherianModule.expandingDependencies(TherianModule.create() .withOperators(PropertyCopier.getInstance(source, target, am.getAnnotation(PropertyCopier.Mapping.class), am.getAnnotation(PropertyCopier.Matching.class))))); @SuppressWarnings({ "unchecked", "rawtypes" }) final Meta<?, ?> result = new Meta(therian, sourceInstance -> Convert.to(target, Positions.<Object>readOnly(source, sourceInstance))); return result; })); this.toString = getClass().getSimpleName() + "[" + type.getJavaClass().getName() + "]"; }
From source file:com.bstek.dorado.data.method.MethodAutoMatchingUtils.java
private static MethodDescriptor describMethodIfMatching(Method method, Type[] requiredTypes, Type[] exactTypes, Type[] optionalTypes, Type returnType) { Type[] argTypes = method.getGenericParameterTypes(); if (argTypes.length > (requiredTypes.length + exactTypes.length + optionalTypes.length)) { return null; }//from w w w .ja va2s .c o m int[] argIndexs = new int[argTypes.length]; int[] argMatchingRates = new int[argTypes.length]; for (int i = 0; i < argIndexs.length; i++) { argIndexs[i] = -1; argMatchingRates[i] = 0; } Type[] requiredTypeArray = new Type[requiredTypes.length]; Type[] exactTypeArray = new Type[exactTypes.length]; Type[] optionalTypeArray = new Type[optionalTypes.length]; System.arraycopy(requiredTypes, 0, requiredTypeArray, 0, requiredTypes.length); System.arraycopy(exactTypes, 0, exactTypeArray, 0, exactTypes.length); System.arraycopy(optionalTypes, 0, optionalTypeArray, 0, optionalTypes.length); // if (returnType != null && !returnType.equals(IgnoreType.class)) { Type methodReturnType = method.getGenericReturnType(); if (isTypeAssignableFrom(returnType, methodReturnType) == 0) { methodReturnType = toNonPrimitiveClass(methodReturnType); if (isTypeAssignableFrom(returnType, methodReturnType) == 0) { return null; } } } // ? for (int i = 0; i < requiredTypeArray.length; i++) { Type requiredType = requiredTypeArray[i]; int matchingArg = -1; for (int j = 0; j < argTypes.length; j++) { Type argType = argTypes[j]; if (isTypeAssignableFrom(argType, requiredType) > 0) { if (matchingArg == -1) { matchingArg = j; } else { Type conflictType = argTypes[matchingArg]; if (argType.equals(conflictType)) { // ???? return null; } else if (isTypeAssignableFrom(conflictType, argType) > 0) { matchingArg = j; } } } } // ? if (matchingArg != -1) { argIndexs[matchingArg] = i; argMatchingRates[matchingArg] = 10; } else { return null; } } // ?? for (int i = 0; i < exactTypeArray.length; i++) { Type exactType = exactTypeArray[i]; int matchingArg = -1; for (int j = 0; j < argTypes.length; j++) { Type argType = argTypes[j]; if (isTypeAssignableFrom(exactType, argType) > 0) { if (matchingArg == -1) { matchingArg = j; } else { // ????? return null; } } } // ?? if (matchingArg != -1) { if (argMatchingRates[matchingArg] == 0) { argIndexs[matchingArg] = requiredTypeArray.length + i; argMatchingRates[matchingArg] = 9; } else { // ????? return null; } } } // ??? int conflictArg = -1, matchingRate = 1000; for (int i = 0; i < argTypes.length; i++) { if (argMatchingRates[i] == 0) { Type argType = argTypes[i]; for (int j = 0; j < optionalTypeArray.length; j++) { Type optionalType = optionalTypeArray[j]; if (optionalType != null) { int rate = isTypeAssignableFrom(argType, optionalType); if (rate == 0) { rate = isTypesCompatible(argType, optionalType); } if (rate > 0) { int originMatchingRate = argMatchingRates[i]; if (originMatchingRate == 0) { argIndexs[i] = requiredTypeArray.length + exactTypeArray.length + j; argMatchingRates[i] = rate; matchingRate += (rate * 2); } else if (conflictArg != -1) { // ???? return null; } else if (originMatchingRate > rate) { matchingRate -= (5 - (originMatchingRate - rate)); // } else if (rate > originMatchingRate) { argIndexs[i] = requiredTypeArray.length + exactTypeArray.length + j; argMatchingRates[i] = rate; matchingRate -= (5 - (rate - originMatchingRate)); // } else { // ???? argIndexs[i] = -1; conflictArg = i; matchingRate -= (argTypes.length * 10); } } } } if (argIndexs[i] != -1) { optionalTypeArray[argIndexs[i] - exactTypeArray.length - requiredTypeArray.length] = null; } } } // ???? if (conflictArg != -1) { Type argType = argTypes[conflictArg]; for (int i = 0; i < optionalTypeArray.length; i++) { Type optionalType = optionalTypeArray[i]; if (optionalType != null && isTypeAssignableFrom(argType, optionalType) > 0) { if (argIndexs[conflictArg] == -1) { argIndexs[conflictArg] = requiredTypeArray.length + i; } else { return null; } } } } int undetermine = 0, undetermineIndex = -1; for (int i = 0; i < argIndexs.length; i++) { if (argIndexs[i] == -1) { undetermine++; undetermineIndex = i; } } // ?????? if (undetermine == 1 && optionalTypes.length == 1) { Type argType = argTypes[undetermineIndex]; if (isSimpleType(argType) && isSimpleType(optionalTypes[0])) { argIndexs[undetermineIndex] = requiredTypeArray.length + exactTypeArray.length; undetermine = 0; matchingRate -= 200; } } if (undetermine > 0) { return null; } return new MethodDescriptor(method, argIndexs, matchingRate); }
From source file:cf.spring.NatsVcapFactoryBean.java
@SuppressWarnings("unchecked") @Override/* w w w .j a va 2 s. co m*/ public void afterPropertiesSet() throws Exception { for (VcapSubscriptionConfig subscription : subscriptions) { final Object bean = subscription.getBean(); final String methodName = subscription.getMethodName(); final Method method = bean.getClass().getMethod(methodName, Publication.class); final ParameterizedType parameterTypes = (ParameterizedType) method.getGenericParameterTypes()[0]; Class<MessageBody<Object>> parameterType = (Class<MessageBody<Object>>) parameterTypes .getActualTypeArguments()[0]; final String queueGroup = subscription.getQueueGroup(); cfNats.subscribe(parameterType, queueGroup, new PublicationHandler<MessageBody<Object>, Object>() { @Override public void onMessage(Publication publication) { try { method.invoke(bean, publication); } catch (IllegalAccessException e) { throw new Error(e); } catch (InvocationTargetException e) { throw new NatsException(e.getTargetException()); } } }); } }
From source file:org.lunarray.model.descriptor.builder.annotation.resolver.matchers.MutatorMatcher.java
/** {@inheritDoc} */ @Override/*from w w w. jav a 2 s . c om*/ public Type extractGenericType(final Method type) { Validate.notNull(type, MutatorMatcher.METHOD_NULL); Type result = null; if (this.matchGenericConditions(type)) { result = type.getGenericParameterTypes()[0]; } return result; }
From source file:org.callimachusproject.rewrite.ProxyPostAdvice.java
public ProxyPostAdvice(String[] bindingNames, FluidType[] bindingTypes, Substitution[] replacers, Method method) { super(bindingNames, bindingTypes, replacers, method); Annotation[][] panns = method.getParameterAnnotations(); Type[] gtypes = method.getGenericParameterTypes(); for (int i = 0; i < panns.length; i++) { if (bindingNames[i] == null) { for (Annotation ann : panns[i]) { if (ann instanceof type) { bodyIndices.put(method, i); String[] media = ((type) ann).value(); bodyFluidType = new FluidType(gtypes[i], media); for (Annotation bann : panns[i]) { if (bann instanceof Iri) { bodyIri = ((Iri) bann).value(); }/*from ww w. j av a2s .c o m*/ } } } } } }