具有通用类类型的Java反射getDeclaredMethod()

时间:2013-08-24 04:42:17

标签: java generics reflection

我在A班有一个方法:

class Parameter {
...
}

class A {
   private <T extends B> void call(T object, Parameter... parameters){
   ...
   }
}

现在我想使用反射来获取方法“call”,

A a = new A();
// My question is what should be arguments in getDeclaredMethod
//Method method = a.getClass().getDeclaredMethod()

THX。

1 个答案:

答案 0 :(得分:6)

它们应该是BParameter[],因为BT的{​​{3}}而varargs是作为数组实现的:

Method method = a.getClass().getDeclaredMethod(
        "call",
        B.class,
        Parameter[].class
);

请注意,您遇到语法错误:<T extends of B>应为<T extends B>

另请注意,您展示它的方法根本不需要是通用的。这也可行:

private void call(B object, Parameter... parameters) { ... }