Java Code Examples for java.lang.reflect.Method#getTypeParameters()

The following examples show how to use java.lang.reflect.Method#getTypeParameters() . 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 check out the related API usage on the sidebar.
Example 1
Source File: InjectionPoint.java    From businessworks with Apache License 2.0 6 votes vote down vote up
private static boolean isValidMethod(InjectableMethod injectableMethod,
    Errors errors) {
  boolean result = true;
  if (injectableMethod.jsr330) {
    Method method = injectableMethod.method;
    if (Modifier.isAbstract(method.getModifiers())) {
      errors.cannotInjectAbstractMethod(method);
      result = false;
    }
    if (method.getTypeParameters().length > 0) {
      errors.cannotInjectMethodWithTypeParameters(method);
      result = false;
    }
  }
  return result;
}
 
Example 2
Source File: GenericMetadataSupport.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Resolve current method generic return type to a {@link GenericMetadataSupport}.
 *
 * @param method Method to resolve the return type.
 * @return {@link GenericMetadataSupport} representing this generic return type.
 */
public GenericMetadataSupport resolveGenericReturnType(Method method) {
    Type genericReturnType = method.getGenericReturnType();
    // logger.log("Method '" + method.toGenericString() + "' has return type : " + genericReturnType.getClass().getInterfaces()[0].getSimpleName() + " : " + genericReturnType);

    if (genericReturnType instanceof Class) {
        return new NotGenericReturnTypeSupport(genericReturnType);
    }
    if (genericReturnType instanceof ParameterizedType) {
        return new ParameterizedReturnType(this, method.getTypeParameters(), (ParameterizedType) method.getGenericReturnType());
    }
    if (genericReturnType instanceof TypeVariable) {
        return new TypeVariableReturnType(this, method.getTypeParameters(), (TypeVariable) genericReturnType);
    }

    throw new MockitoException("Ouch, it shouldn't happen, type '" + genericReturnType.getClass().getCanonicalName() + "' on method : '" + method.toGenericString() + "' is not supported : " + genericReturnType);
}
 
Example 3
Source File: TypeVariableTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
public void testMultipleTypeVariablesOnMethod() throws Exception {
    Class<? extends E> clazz = E.class;
    Method method = clazz.getDeclaredMethod("e");

    TypeVariable<?>[] typeParameters = method.getTypeParameters();
    assertEquals(3, typeParameters.length);
    assertEquals("Q", typeParameters[0].getName());
    assertEquals(method, typeParameters[0].getGenericDeclaration());
    assertEquals("Q", typeParameters[0].toString());
    assertEquals("Q", typeParameters[0].getTypeName());

    assertEquals("R", typeParameters[1].getName());
    assertEquals(method, typeParameters[1].getGenericDeclaration());
    assertEquals("R", typeParameters[1].toString());
    assertEquals("R", typeParameters[1].getTypeName());

    assertEquals("S", typeParameters[2].getName());
    assertEquals(method, typeParameters[2].getGenericDeclaration());
    assertEquals("S", typeParameters[2].toString());
    assertEquals("S", typeParameters[2].getTypeName());
}
 
Example 4
Source File: AnnotationConstruct.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    String methodName = method.getName();
    int parameters = method.getTypeParameters().length;
    if (parameters == 0 && annotationElement.hasValue(methodName)) {
        return annotationElement.getValue(methodName);
    }
    throw new UnsupportedOperationException("Flight Recorder proxy only supports members declared in annotation interfaces, i.e. not toString, equals etc.");
}
 
Example 5
Source File: AnnotationConstruct.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    String methodName = method.getName();
    int parameters = method.getTypeParameters().length;
    if (parameters == 0 && annotationElement.hasValue(methodName)) {
        return annotationElement.getValue(methodName);
    }
    throw new UnsupportedOperationException("Flight Recorder proxy only supports members declared in annotation interfaces, i.e. not toString, equals etc.");
}
 
Example 6
Source File: AnnotationConstruct.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    String methodName = method.getName();
    int parameters = method.getTypeParameters().length;
    if (parameters == 0 && annotationElement.hasValue(methodName)) {
        return annotationElement.getValue(methodName);
    }
    throw new UnsupportedOperationException("Flight Recorder proxy only supports members declared in annotation interfaces, i.e. not toString, equals etc.");
}
 
Example 7
Source File: GenericMethodsTests.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public void testIndependencyOfMethodTypeParameters() throws Exception {
    Method method0 = clazz.getMethod("paramNoReturn", Object.class);
    TypeVariable<Method> typeParameter0 = method0.getTypeParameters()[0];

    Method method1 = clazz.getMethod("noParamNoReturn");
    TypeVariable<Method> typeParameter1 = method1.getTypeParameters()[0];

    //Generic method type parameters NAMES are equal
    assertEquals(typeParameter0.getName(), typeParameter1.getName());
    //Generic method type PARAMETERS are not equal
    assertNotEquals(typeParameter0, typeParameter1);
}
 
Example 8
Source File: TypeVariableTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public void testSimpleTypeVariableOnMethod() throws Exception{
    Class<? extends B> clazz = B.class;
    Method method = clazz.getDeclaredMethod("b");
    TypeVariable<Method>[] typeParameters = method.getTypeParameters();
    assertLenghtOne(typeParameters);
    TypeVariable<Method> typeVariable = typeParameters[0];
    assertEquals(method, typeVariable.getGenericDeclaration());
    assertEquals("T", typeVariable.getName());
    assertEquals("T", typeVariable.toString());
    assertEquals("T", typeVariable.getTypeName());
    Type[] bounds = typeVariable.getBounds();
    assertLenghtOne(bounds);
    assertEquals(Object.class, bounds[0]);
}
 
Example 9
Source File: ModelRuleInspector.java    From pushfish-android with BSD 2-Clause "Simplified" License 4 votes vote down vote up
private void validate(Method ruleMethod) {
    // TODO validations on method: synthetic, bridge methods, varargs, abstract, native
    if (ruleMethod.getTypeParameters().length > 0) {
        throw invalid(ruleMethod, "cannot have type variables (i.e. cannot be a generic method)");
    }
}
 
Example 10
Source File: GenericTypeResolver.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * 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.
 * <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 class="code">{@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})
 * @param classLoader the ClassLoader to resolve class names against, if necessary
 * (may be {@code null})
 * @return the resolved target return type, the standard return type, or {@code null}
 * @since 3.2.5
 * @deprecated as of Spring Framework 4.3.8, superseded by {@link ResolvableType} usage
 */
@Deprecated
public static Class<?> resolveReturnTypeForGenericMethod(Method method, Object[] args, ClassLoader classLoader) {
	Assert.notNull(method, "Method must not be null");
	Assert.notNull(args, "Argument array must not be null");

	TypeVariable<Method>[] declaredTypeVariables = method.getTypeParameters();
	Type genericReturnType = method.getGenericReturnType();
	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)) {
			locallyDeclaredTypeVariableMatchesReturnType = true;
			break;
		}
	}

	if (locallyDeclaredTypeVariableMatchesReturnType) {
		for (int i = 0; i < methodArgumentTypes.length; i++) {
			Type currentMethodArgumentType = methodArgumentTypes[i];
			if (currentMethodArgumentType.equals(genericReturnType)) {
				return args[i].getClass();
			}
			if (currentMethodArgumentType instanceof ParameterizedType) {
				ParameterizedType parameterizedType = (ParameterizedType) currentMethodArgumentType;
				Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
				for (Type typeArg : actualTypeArguments) {
					if (typeArg.equals(genericReturnType)) {
						Object arg = args[i];
						if (arg instanceof Class) {
							return (Class<?>) arg;
						}
						else if (arg instanceof String && classLoader != null) {
							try {
								return classLoader.loadClass((String) arg);
							}
							catch (ClassNotFoundException ex) {
								throw new IllegalStateException(
										"Could not resolve specific class name argument [" + arg + "]", ex);
							}
						}
						else {
							// Consider adding logic to determine the class of the typeArg, if possible.
							// For now, just fall back...
							return method.getReturnType();
						}
					}
				}
			}
		}
	}

	// Fall back...
	return method.getReturnType();
}
 
Example 11
Source File: GenericTypeResolver.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
/**
 * 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.
 * <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 class="code">{@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})
 * @param classLoader the ClassLoader to resolve class names against, if necessary
 * (may be {@code null})
 * @return the resolved target return type, the standard return type, or {@code null}
 * @since 3.2.5
 * @see #resolveReturnType
 */
public static Class<?> resolveReturnTypeForGenericMethod(Method method, Object[] args, ClassLoader classLoader) {
	Assert.notNull(method, "Method must not be null");
	Assert.notNull(args, "Argument array must not be null");

	TypeVariable<Method>[] declaredTypeVariables = method.getTypeParameters();
	Type genericReturnType = method.getGenericReturnType();
	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)) {
			locallyDeclaredTypeVariableMatchesReturnType = true;
			break;
		}
	}

	if (locallyDeclaredTypeVariableMatchesReturnType) {
		for (int i = 0; i < methodArgumentTypes.length; i++) {
			Type currentMethodArgumentType = methodArgumentTypes[i];
			if (currentMethodArgumentType.equals(genericReturnType)) {
				return args[i].getClass();
			}
			if (currentMethodArgumentType instanceof ParameterizedType) {
				ParameterizedType parameterizedType = (ParameterizedType) currentMethodArgumentType;
				Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
				for (Type typeArg : actualTypeArguments) {
					if (typeArg.equals(genericReturnType)) {
						Object arg = args[i];
						if (arg instanceof Class) {
							return (Class<?>) arg;
						}
						else if (arg instanceof String && classLoader != null) {
							try {
								return classLoader.loadClass((String) arg);
							}
							catch (ClassNotFoundException ex) {
								throw new IllegalStateException(
										"Could not resolve specific class name argument [" + arg + "]", ex);
							}
						}
						else {
							// Consider adding logic to determine the class of the typeArg, if possible.
							// For now, just fall back...
							return method.getReturnType();
						}
					}
				}
			}
		}
	}

	// Fall back...
	return method.getReturnType();
}
 
Example 12
Source File: GenerateIfaceCommand.java    From baratine with GNU General Public License v2.0 4 votes vote down vote up
private static void methodToString(StringBuilder sb,
                                   Method method,
                                   boolean isUseReturnType)
{
  if (isUseReturnType) {
    TypeVariable []typeVars = method.getTypeParameters();

    if (typeVars.length > 0) {
      sb.append("<");

      for (int i = 0; i < typeVars.length; i++) {
        if (i != 0) {
          sb.append(",");
        }

        sb.append(typeVars[i]);
      }

      sb.append(">");
      sb.append(" ");
    }

    sb.append("void " + method.getName() + "(");
  }

  Parameter []parameters = method.getParameters();
  for (int i = 0; i < parameters.length; i++ ) {
    if (i > 0) {
      sb.append(", ");
    }

    Parameter param = parameters[i];

    if (isUseReturnType && param.getParameterizedType() != null) {
      typeToString(sb, param.getParameterizedType(), false);
    }
    else {
      typeToString(sb, param.getType(), false);
    }

    sb.append(" " + param.getName());
  }

  if (isUseReturnType) {
    Type returnType = method.getGenericReturnType();

    if (returnType != void.class) {
      if (parameters.length > 0) {
        sb.append(", ");
      }

      sb.append("Result<");
      typeToString(sb, returnType, true);
      sb.append("> __result");
    }
  }

  sb.append(")");
}
 
Example 13
Source File: CxfCdiAutoSetup.java    From openwebbeans-meecrowave with Apache License 2.0 4 votes vote down vote up
private static String toSimpleString(final Method mtd) {
    try {
        final StringBuilder sb = new StringBuilder();
        final Type[] typeparms = mtd.getTypeParameters();
        if (typeparms.length > 0) {
            boolean first = true;
            sb.append("<");
            for (Type typeparm : typeparms) {
                if (!first) {
                    sb.append(",");
                }
                sb.append(name(typeparm));
                first = false;
            }
            sb.append("> ");
        }

        final Type genRetType = mtd.getGenericReturnType();
        sb.append(name(genRetType)).append(" ");
        sb.append(mtd.getName()).append("(");
        final Type[] params = mtd.getGenericParameterTypes();
        for (int j = 0; j < params.length; j++) {
            sb.append(name(params[j]));
            if (j < (params.length - 1)) {
                sb.append(", ");
            }
        }
        sb.append(")");
        final Type[] exceptions = mtd.getGenericExceptionTypes();
        if (exceptions.length > 0) {
            sb.append(" throws ");
            for (int k = 0; k < exceptions.length; k++) {
                sb.append(name(exceptions[k]));
                if (k < (exceptions.length - 1)) {
                    sb.append(",");
                }
            }
        }
        return sb.toString();
    } catch (final Exception e) {
        return "<" + e + ">";
    }
}
 
Example 14
Source File: ModelRuleInspector.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 4 votes vote down vote up
private void validate(Method ruleMethod) {
    // TODO validations on method: synthetic, bridge methods, varargs, abstract, native
    if (ruleMethod.getTypeParameters().length > 0) {
        throw invalid(ruleMethod, "cannot have type variables (i.e. cannot be a generic method)");
    }
}
 
Example 15
Source File: Logs.java    From tomee with Apache License 2.0 4 votes vote down vote up
public static String toSimpleString(final Method mtd) {
    try {
        final StringBuilder sb = new StringBuilder();
        final Type[] typeparms = mtd.getTypeParameters();
        if (typeparms.length > 0) {
            boolean first = true;
            sb.append("<");
            for (Type typeparm : typeparms) {
                if (!first) {
                    sb.append(",");
                }
                sb.append(name(typeparm));
                first = false;
            }
            sb.append("> ");
        }

        final Type genRetType = mtd.getGenericReturnType();
        sb.append(name(genRetType)).append(" ");
        sb.append(mtd.getName()).append("(");
        final Type[] params = mtd.getGenericParameterTypes();
        for (int j = 0; j < params.length; j++) {
            sb.append(name(params[j]));
            if (j < (params.length - 1)) {
                sb.append(", ");
            }
        }
        sb.append(")");
        final Type[] exceptions = mtd.getGenericExceptionTypes();
        if (exceptions.length > 0) {
            sb.append(" throws ");
            for (int k = 0; k < exceptions.length; k++) {
                sb.append(name(exceptions[k]));
                if (k < (exceptions.length - 1)) {
                    sb.append(",");
                }
            }
        }
        return sb.toString();
    } catch (Exception e) {
        return "<" + e + ">";
    }
}
 
Example 16
Source File: GenericReflectionTestsBase.java    From j2objc with Apache License 2.0 3 votes vote down vote up
/**
 * Returns the type parameter of the declaring method.
 *
 * @param method
 *            the declaring method
 * @return the type parameter of the method
 */
public TypeVariable<Method> getTypeParameter(Method method) {
    TypeVariable<Method>[] typeParameters = method.getTypeParameters();
    assertLenghtOne(typeParameters);
    TypeVariable<Method> typeParameter = typeParameters[0];
    return typeParameter;
}