2013-01-16 65 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