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()


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM