Java反射:在运行时检查方法参数的类型

use*_*880 9 java reflection

我需要检查方法第一个参数的类型是否List<Class<? extends Exception>>.任何人都可以提出比将其与String相比更好的解决方案吗?

Method m = Foo.class.getMethod("m1", List.class);
if (m.getGenericParameterTypes()[0].toString().equals("java.util.List<java.lang.Class<? extends java.lang.Exception>>")) {
  ...
}
Run Code Online (Sandbox Code Playgroud)

我的意思是这样的:

List.class.isAssignableFrom((Class<?>)((ParameterizedType)m.getGenericParameterTypes()[0]).getRawType()));
Run Code Online (Sandbox Code Playgroud)

这检查它是否是一个列表.但我如何检查Class<? extends Exception>该类型的部分?

Ran*_*man 5

刚刚试过以下,它似乎工作:

// package whatever.your.package.happens.to.be;

import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.WildcardType;
import java.util.List;

public class ReflectionTest {
  public static void main(String[] args) throws NoSuchMethodException, SecurityException {
    Method method = ReflectionTest.class.getMethod("method", List.class);
    ParameterizedType listType = (ParameterizedType)method.getGenericParameterTypes()[0];
    ParameterizedType classType = (ParameterizedType)listType.getActualTypeArguments()[0];
    WildcardType genericType = (WildcardType)classType.getActualTypeArguments()[0];
    Class<?> genericClass = (Class<?>)genericType.getUpperBounds()[0];

    boolean isException = Exception.class.isAssignableFrom(genericClass);
    // vvv Prints out "Is Class<? extends Exception>: true"
    System.out.println("Is Class<? extends Exception>: " + isException);

    boolean isRuntimeException = RuntimeException.class.isAssignableFrom(genericClass);
    // vvv Prints out "Is Class<? extends RuntimeException>: false"
    System.out.println("Is Class<? extends RuntimeException>: " + isRuntimeException);
  }

  public void method(List<Class<? extends Exception>> exceptionClasses) {
    // Do something with "exceptionClasses," I would imagine...
  }
}
Run Code Online (Sandbox Code Playgroud)

编辑:好的,这次是实时的.我刚才注意到它是,List<Class<? extends Exception>>而不是List<? extends Exception>.所以这个(希望)最终的解决方案实际上应该符合这个案例.