2013-01-31 94 views
6

例獲取接口名稱:我想從實現類

List<String> list = new ArrayList<String>(); 
//This would give me the class name for the list reference variable. 
list.getClass().getSimpleName(); 

我想從list參考變量獲取接口名稱。 有沒有辦法做到這一點?

回答

9

使用Reflection可以調用Class.getInterfaces()方法,該方法返回您的類實現的Array of Interfaces

System.out.println(list.getClass().getInterfaces()[0]); 

得到公正的名稱

System.out.println(list.getClass().getInterfaces()[0].getSimpleName); 
+2

你也可以自己調用這些接口擴展接口。 – Guillaume

+0

@Guillaume好點,他們將是類實現順序,例如interface [0]將java.util.List和interface [1]將java.util.RandomAccess – PermGenError

+0

如果您想要獲得Collection接口在第一次調用返回的接口上調用getInterface()。 – Guillaume

2
Class aClass = ... //obtain Class object. 
Class[] interfaces = aClass.getInterfaces();