首页 > 代码库 > 有一个反射的小程序引出的问题

有一个反射的小程序引出的问题

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 void rr(double c,Method f){
        try{
            double x=(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(有待理解)

有一个反射的小程序引出的问题