手册中的 invoke 方法描述是这样子的:
public Object invoke(Object obj,
Object... args)
throws IllegalAccessException,
IllegalArgumentException,
InvocationTargetException
为什么执行方法非要传一个 obj 对象?
我写了个例子:
public class Test01 {
public void m01(String info){
System.out.println(info);
}
}
public class Reflect {
public static void main(String[] args) {
try {
Method method = Class.forName("com.hack4b.test.Father").getMethod("m01", String.class);
//method.invoke(?, "Hello"); //问号里的参数为 null 会错误
} catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
我只想通过反射机制调用 Test 类的 m01 方法,并传参字符串 Hello 给 info ,然后通过 m01 方法打印出来。
我一直困惑, invoke 方法第一个参数到底是干什么用的?要执行方法,直接传参数被调用方法的参数就好了啊?为什么还要在第一个参数加一个 Object 类型的对象?
手册上是这么解释的:
Parameters:
obj - the object the underlying method is invoked from
args - the arguments used for the method call
看上去,意思是 obj 是调用方法的对象,也就是说指明是哪一个对象去调用方法。
我写的例子中,我是在 main 方法中通过反射机制获取的 m01 方法并执行,按照上述的意思,我是想用当前对象去调用 m01 方法,于是我就传了个 this 进去,结果 IDE 提示语法错误: Cannot use this in a static context
然后我又声明了一个 Object 对象传进去,程序也没法跑,还抛异常: java.lang.IllegalArgumentException: object is not an instance of declaring class
难道是我没理解对?