代码实例:
package com.reflection.Field;
import java.lang.reflect.Field;
public class ReflectionFieldTest {
public static void main(String args[]){
/**
* 反射获得成员变量,Field 代表某个类中的成员你变量
*/
ReflectionPoint rp = new ReflectionPoint(5, 10);
Class cls = null;
try {
cls = Class.forName("com.reflection.Field.ReflectionPoint"); //获取ReflectionPoint的Class对象
Field fieldx = cls.getField("x"); //获得成员变量x保存在fieldx中
int x = (int)fieldx.get(rp); //获得成员变量具体值
System.out.println(x);
//私有成员变量的获取
Field fieldy = cls.getDeclaredField("y"); //getDeclaredField可以获取私有的成员变量,不管什么权限的成员变量都可以获取
fieldy.setAccessible(true); //y成员变量是私有,这里设置为true表示可以访问,不设置访问会出现IllegalAccessException
int y = (int)fieldy.get(rp);
System.out.println(y);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchFieldException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
package com.reflection.Field;
public class ReflectionPoint {
public int x;
private int y;