1. 程式人生 > >有一個反射的小程序引出的問題

有一個反射的小程序引出的問題

pre 創建 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 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(有待理解)

有一個反射的小程序引出的問題