Class类中getMethods() 与getDeclaredMethods() 方法的区别

一:jdk API中关于两个方法的解释

1:getMethods(),该方法是获取本类以及父类或者父接口中所有的公共方法(public修饰符修饰的)

2:getDeclaredMethods(),该方法是获取本类中的所有方法,包括私有的(private、protected、默认以及public)的方法。

二:代码演示

1:定义父类ReflectionParent.java

复制代码
 1 /**
 2  * 
 3  */
 4 package com.paic.reflection;
 5 
 6 /**
 7  * @author Administrator
 8  * 
 9  */
10 public class ReflectionParent {
11     public void start() {
12         System.out.println("starting...");
13     }
14 
15     protected void eat() {
16         System.out.println("eating...");
17     }
18 
19     void end() {
20         System.out.println("ending...");
21     }
22 
23     @SuppressWarnings("unused")
24     private void sing() {
25         System.out.println("sing...");
26     }
27 }
复制代码

2:定义子类ReflectionDemo1继承父类,定义两个自己的方法和两个测试方法

复制代码
 1 /**
 2  * 
 3  */
 4 package com.paic.reflection;
 5 
 6 import java.lang.reflect.Method;
 7 
 8 import org.junit.Test;
 9 
10 /**
11  * @author Administrator
12  * 
13  */
14 public class ReflectionDemo1 extends ReflectionParent {
15 
16     @SuppressWarnings("unused")
17     private void read() {
18         System.out.println("reading...");
19     }
20 
21     public void write() {
22         System.out.println("writing...");
23     }
24 
25     /**
26      * @param args
27      */
28     @Test
29     public void testGetMethods() {
30         Method[] methods = this.getClass().getMethods();
31         for (Method m : methods) {
32             System.out.println(m.getName());
33         }
34     }
35 
36     @Test
37     public void testGetDeclaredMethods() {
38         Method[] methods = this.getClass().getDeclaredMethods();
39         for (Method m : methods) {
40             System.out.println(m.getName());
41         }
42     }
43 
44 }
复制代码

3:运行结果

a:运行testGetMethods()方法

b:运行testGetDeclaredMethods()方法

三:其他的方法,类似字段以及构造方法和方法类似

1:getFileds()与getDeclaredFileds()

2:getConstructors()与getDeclaredConstructors()

 

    学习是一生的功课,关注不迷路,一起进步

 

 

posted @   程序员三藏  阅读(37002)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示