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 @ 2016-08-31 22:27  warrior1234  阅读(36610)  评论(0编辑  收藏  举报