首页 > 代码库 > 有一个反射的小程序引出的问题
有一个反射的小程序引出的问题
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(有待理解)
有一个反射的小程序引出的问题
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。