好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

java中Class.getMethods()和Class.getDeclaredMethods()

在java中,可以根据class类的对象,知道某个类(接口)的一些属性(成员 ,方法,注释,注解)等。由于最近的工作中用到了这些,其中需要在代码中格局反射知道某些类的方法,查看文档的时候,看到了getmethods()和getdeclaredmethods()的差异。虽然两者都能实现目的,但个人觉得还是有必要区分下。

  jdk api(1.6)文档中是这样翻译两个方法的:

getmethods():

  返回一个包含某些 method 对象的数组,这些对象反映此 class 对象所表示的类或接口(包括那些由该类或接口声明的以及从超类和超接口继承的那些的类或接口)的公共 member 方法。数组类返回从 object 类继承的所有(公共)member 方法。返回数组中的元素没有排序,也没有任何特定的顺序。如果此 class 对象表示没有公共成员方法的类或接口,或者表示一个基本类型或 void,则此方法返回长度为 0 的数组。类初始化方法 <clinit> 不包含在返回的数组中。如果类声明了带有相同参数类型的多个公共成员方法,则它们都会包含在返回的数组中。

getdeclaredmethods():

  返回 method 对象的一个数组,这些对象反映此 class 对象表示的类或接口声明的所有方法,包括公共、保护、默认(包)访问和私有方法,但不包括继承的方法。返回数组中的元素没有排序,也没有任何特定的顺序。如果该类或接口不声明任何方法,或者此 class 对象表示一个基本类型、一个数组类或 void,则此方法返回一个长度为 0 的数组。类初始化方法 <clinit> 不包含在返回数组中。如果该类声明带有相同参数类型的多个公共成员方法,则它们都包含在返回的数组中。

  大致上来看,两个方法的区别主要在于:getmethods()返回的是该类以及超类的公共方法。getdeclaredmethods()返回该类本身自己声明的包括公共、保护、默认(包)访问和私有方法,但并不包括超类中的方法。比如如下列子:

?

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

32

33

34

public class testobject

{

   private void method1()

   {

   }

   public void method2()

   {

   }

   void method3()

   {

   }

   protected void method4()

   {

   }

}

public class testclass

{

   public static void main(string[] args)

   {

     method[] methods = testobject. class .getmethods();

     system.out.println( "getmethods():" );

     for (method method : methods)

     {

       system.out.println(method.getname());

     }

     method[] methods2 = testobject. class .getdeclaredmethods();

     system.out.println( "===========================" );

     system.out.println( "getdeclaredmethods():" );

     for (method method : methods2)

     {

       system.out.println(method.getname());

     }

   }

}

运行testclass结果:

getmethods():
method2
wait
wait
wait
equals
tostring
hashcode
getclass
notify
notifyall
===========================
getdeclaredmethods():
method1
method2
method3
method4

  很明显getmethods()就返回一个自己声明的method2()方法,其余的方法全部是来自object类。 getdeclaredmethods() 返回了自生声明的四个方法。两个方法的主要区别就在这里吧。

另外,返回method数组为0 的情况也是jdk按照文档上介绍的一样。比如]空]接口,基本类型:

?

1

2

3

4

public interface testinterface

{

}

//两种方法返回的都是空

以及基本类型:两种方法返回的也都是空

?

1

2

method[] methods = int . class .getmethods();

method[] methods2 = int . class .getdeclaredmethods();

总结:其实class中有很多相似的方法比如: getannotations() 和 getdeclaredannotations(), 以及getfields()和getdeclaredfields()等等,不同之处和上面基本一样

总结

以上所述是小编给大家介绍的java中class.getmethods()和class.getdeclaredmethods()方法的区别,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对网站的支持!

原文链接:https://www.cnblogs.com/wy697495/archive/2018/09/12/9631909.html

查看更多关于java中Class.getMethods()和Class.getDeclaredMethods()的详细内容...

  阅读:44次