网站首页 美食营养 游戏数码 手工爱好 生活家居 健康养生 运动户外 职场理财 情感交际 母婴教育 时尚美容 知识问答

java反射调用方法

时间:2024-10-12 09:45:26

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反射调用方法

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

java反射调用方法

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

java反射调用方法

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

java反射调用方法
© 2025 小知经验
信息来自网络 所有数据仅供参考
有疑问请联系站长 site.kefu@gmail.com