Java反射无法正常工作

时间:2011-08-18 09:58:57

标签: java reflection

我有这样的代码

final Method method = XYZClass.class.getDeclaredMethod(METHOD_NAME, new Class[] {List.class, List.class});
 method.setAccessible(true);
final List<Integer> output = (List<Integer>) method.invoke(METHOD_NAME, new Object[] {inputRecords, foo});

inputRecords是一个对象列表,foo是一个对象。

我得到的对象不是声明类的实例。??

1 个答案:

答案 0 :(得分:4)

您正尝试在方法名称(即字符串)上调用方法。您应该在对XYZClass

的实例的引用上调用它
XYZClass xyz = ...;
final List<Integer> output = (List<Integer>) method.invoke(xyz,
                                     new Object[] {inputRecords, foo});

如果是静态方法,请使用null作为第一个参数。