2013-01-16 117 views
0

獲取班級成員我有班級名稱(作爲String),我想獲取所有成員及其類型。我知道我需要使用反射,但是如何?從班級名稱

舉例來說,如果我有

class MyClass { 
    Integer a; 
    String b; 
} 

我怎麼得到的ab的類型和名稱?

+1

看一看的[甲骨文反射引導](http://docs.oracle.com/javase/6/docs/technotes/guides/reflection/index.html )包含教程,指南,示例和API文檔的鏈接。 – zoom

回答

1

如果類已經被JVM加載,你可以使用類稱爲類的靜態方法。 forName(String className);它會返回給你一個反射對象的句柄。

你會怎麼做:

//get class reflections object method 1 
Class aClassHandle = Class.forName("MyClass"); 

//get class reflections object method 2(preferred) 
Class aClassHandle = MyClass.class; 

//get a class reflections object method 3: from an instance of the class 
MyClass aClassInstance = new MyClass(...); 
Class aClassHandle = aClassInstance.getClass(); 



//get public class variables from classHandle 
Field[] fields = aClassHandle.getFields(); 

//get all variables of a class whether they are public or not. (may throw security exception) 
Field[] fields = aClassHandle.getDeclaredFields(); 

//get public class methods from classHandle 
Method[] methods = aClassHandle.getMethods(); 

//get all methods of a class whether they are public or not. (may throw security exception) 
Method[] methods = aClassHandle.getDeclaredMethods(); 

//get public class constructors from classHandle 
Constructor[] constructors = aClassHandle.getConstructors(); 

//get all constructors of a class whether they are public or not. (may throw security exception) 
Constructor[] constructors = aClassHandle.getDeclaredConstructors(); 

爲了得到一個名爲b。從MyClass的變量,一個可以做。

Class classHandle = Class.forName("MyClass"); 
Field b = classHandle.getDeclaredField("b"); 

如果b是整數類型,爲了得到它的值,我會做。

int bValue = (Integer)b.get(classInstance);//if its an instance variable` 

int bValue = (Integer)b.get(null);//if its a static variable 
+0

假設我不知道字段類型,我應該怎麼做?你在做int bValue =(Integer)b.get(classInstance);但我有類成員列表(我使用Field [] fields = classHandle.getDeclaredFields();)我想知道各自的類型。我不能使用你的代碼,因爲你正在做鑄造,我不知道字段類型 –

+0

,如果你有一些Field f,並且你想獲得類型的類句柄,你可以使用f.getType();您也可以將其更改爲Object bValue = b.get(...); –

+0

也,如果該字段不公開,您將不得不調用field.setAccessible(true);在獲得之前,或者你會得到一個安全例外 –

1

首先獲取類:

Class clazz=ClassforName("NameOfTheClass") 

多問了所有其他信息 Class API