创建 pri get sys 实例 logs exception .get
- public class second{
- public static void main(String[]args){
- try{
- Method sqrt=Math.class.getMethod("sqrt",double.class);
- rr(3,sqrt);
- }catch(Exception e){};
- }
- private static voidrr(double c,Method f){
- try{
- doublex=(double)f.invoke(null, c);
- System.out.printf("%.3f|%.3f \n",x,c);
- System.out.println(f);
- }catch(Exception e){};
- }
- }
利用 reflect 去获得该类的方法,期间我在本类中并没有添加 "static",然后编译运行:
Cannot make a static reference to the non-static method rr(double, Method) from the type second
究其原因,JVM 的机制决定了 static 方法中是不能直接调用该类的其它非 static 方法的,因为非 static 需要用 this 指代自身的方法,并且 static 在编译的时候已经在内存上进行创建,
而非 static 的方法需要进行实例化操作以后装入 内存。
关于 invoke(有待理解)
有一个反射的小程序引出的问题
来源: http://www.bubuko.com/infodetail-2141659.html