java反射调用方法

2025-05-24 05:51:34

1、Talk is cheap.Show me the code.code:package chapter3;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;/*** Created by MyWorld on 2016/3/16.*/public class RefactorInvokeMethodDemo { public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, InstantiationException { Class<Business> businessClass = Business.class; Business business = businessClass.newInstance(); Method sayHelloMethod = businessClass.getDeclaredMethod("sayHello", String.class); Object result = sayHelloMethod.invoke(business, "Baidu文库"); System.out.println(result); }}class Business { public String sayHello(String guestName) { return "Hello ," + guestName; }}

java反射调用方法
java反射调用方法

2、执行上面的代码,看看会输出的结果是什么?是不是期待的“Hello ,Baidu文库”还是真是!!!应该是嘛,完全是按api来的喽

java反射调用方法

3、知其然,知其所以然后。来分析下代码:(1)获取一个类定义:Business.class(2)根据类定义,实例化一个实例business:businessClass.newInstance();(3)根据类定义,使用apigetDeclaredMethod获取指定的Method(4)调用获取的Method:sayHelloMethod.invoke(business, "Baidu文库");

java反射调用方法

4、能不调用private的方法呢?是可以的。Show the code.Code:private String sayHello(String guestName) { return "Hello ," + guestName;}

java反射调用方法

5、执行上面的代码,看看是否能调用成功报错了。。。错误信息:Exception in thread "main" java.lang.Illega造婷用痃lAccessException: Class chapter3.RefactorInvokeMethodDemo can not access a member of class chapter3.Business with modifiers "private" at sun.reflect.Reflection.ensureMemberAccess(Reflection.java:65) at java.lang.reflect.Method.invoke(Method.java:588) at chapter3.RefactorInvokeMethodDemo.main(RefactorInvokeMethodDemo.java:15) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)

java反射调用方法

6、哦。还需要设置一个地方,更改方法的private属性Code:Method sayHelloMethod = businessClass.getDeclaredMethod("sayHello", String.class);sayHelloMethod.setAccessible(true);

java反射调用方法

7、执行最新的代码,看看是否正常了。ok,看到熟悉的输出结果了!O了!

java反射调用方法
声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢