反射获取方法对象

/**
目标:反射——获取Method方法对象

反射获取类的Method方法对象:
1、Method getMethod(String name,Class...args);
根据方法名和参数类型获得对应的方法对象,只能获得public的

2、Method getDeclaredMethod(String name,Class...args);
根据方法名和参数类型获得对应的方法对象,包括private的

3、Method[] getMethods();
获得类中的所有成员方法对象,返回数组,只能获得public修饰的且包含父类的

4、Method[] getDeclaredMethods();
获得类中的所有成员方法对象,返回数组,只获得本类申明的方法。

Method的方法执行:
Object invoke(Object obj, Object... args)
参数一:触发的是哪个对象的方法执行。
参数二: args:调用方法时传递的实际参数
*/
public class MethodDemo01 {
/**
* 1.获得类中的所有成员方法对象
*/
@Test
public void getDeclaredMethods(){
// a.获取类对象
Class c = Dog.class;
// b.提取全部方法,包括私有的
Method[] methods = c.getDeclaredMethods();
// c.遍历全部方法
for (Method method :methods) {
System.out.println(method.getName()+" 返回值类型:"+method.getReturnType()+" 参数个数"+method.getParameterCount());
}

}

/**
* 2. 获取某个方法对象
*/
@Test
public void getDeclardMethod() throws Exception {
// a.获取类对象
Class c = Dog.class;
// b.提取单个方法对象
Method m = c.getDeclaredMethod("eat");
Method m2 = c.getDeclaredMethod("eat",String.class);

//暴力打开权限
m2.setAccessible(true);


Constructor cons = c.getDeclaredConstructor(String.class);
cons.setAccessible(true);
Dog dog = (Dog)cons.newInstance("小白");
Object obj = m2.invoke(dog,"骨头");
System.out.println(obj);
//注意:方法如果没有结果回来的, 那么返回的是null

}
}

posted on   我要当程序源  阅读(229)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示