Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/visual-studio-2012/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 从类名获取类的成员_Java_Reflection - Fatal编程技术网

Java 从类名获取类的成员

Java 从类名获取类的成员,java,reflection,Java,Reflection,我有一个类名(作为字符串),我想获取所有成员及其类型。我知道我需要使用反射,但是如何使用呢 例如,如果我有 class MyClass { Integer a; String b; } 如何获取a和b的类型和名称?首先获取类: Class clazz=ClassforName("NameOfTheClass") 而不是询问所有其他信息 如果jvm已经加载了类,那么可以使用名为Class.forName(String className)的类的静态方法;它将返回反射对象的句柄

我有一个类名(作为
字符串
),我想获取所有成员及其类型。我知道我需要使用反射,但是如何使用呢

例如,如果我有

class MyClass {
    Integer a;
    String b;
}
如何获取
a
b
的类型和名称?

首先获取类:

Class clazz=ClassforName("NameOfTheClass") 
而不是询问所有其他信息

如果jvm已经加载了类,那么可以使用名为Class.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();
要从MyClass中获取名为b的变量,可以这样做

Class classHandle = Class.forName("MyClass");
Field b = classHandle.getDeclaredField("b");
如果b是整型的,为了得到它的值,我会这样做

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


看一看包含教程、指南、示例和API文档链接的。假设我不知道字段类型,我该如何做?您正在执行int bValue=(整数)b.get(classInstance);但我有类成员列表(我使用Field[]fields=classHandle.getDeclaredFields();),我想知道各自的类型。我不能使用您的代码,因为您正在执行强制转换,我不知道字段类型如果您有一些字段f,并且您想获得其类型的类句柄,请使用f.getType();您也可以将其更改为Object bValue=b.get(…);此外,如果该字段不是公共字段,则必须调用field.setAccessible(true);在获取之前,否则您将获得一个安全异常
int bValue = (Integer)b.get(null);//if its a static variable