6
例獲取接口名稱:我想從實現類
List<String> list = new ArrayList<String>();
//This would give me the class name for the list reference variable.
list.getClass().getSimpleName();
我想從list
參考變量獲取接口名稱。 有沒有辦法做到這一點?
例獲取接口名稱:我想從實現類
List<String> list = new ArrayList<String>();
//This would give me the class name for the list reference variable.
list.getClass().getSimpleName();
我想從list
參考變量獲取接口名稱。 有沒有辦法做到這一點?
使用Reflection可以調用Class.getInterfaces()
方法,該方法返回您的類實現的Array of Interfaces
。
System.out.println(list.getClass().getInterfaces()[0]);
得到公正的名稱
System.out.println(list.getClass().getInterfaces()[0].getSimpleName);
Class aClass = ... //obtain Class object.
Class[] interfaces = aClass.getInterfaces();
你也可以自己調用這些接口擴展接口。 – Guillaume
@Guillaume好點,他們將是類實現順序,例如interface [0]將java.util.List和interface [1]將java.util.RandomAccess – PermGenError
如果您想要獲得Collection接口在第一次調用返回的接口上調用getInterface()。 – Guillaume