在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