使用反射访问属性值

public class Student {
	
	private String name;	
	
}
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;


public class Test {

	public static void main(String[] args) throws Exception {
		
		String str_class = "Student";
		String str_field_1 = "name";
		
		//获取Student类的一个实例
		Class<?> class_1 = Class.forName(str_class);
		Constructor<?> constructor = class_1.getConstructor();
		Object obj = constructor.newInstance();
		
		//Field field1 = class_1.getField(str_field_1);//getField只能获取到public的域
		Field field1 = class_1.getDeclaredField(str_field_1);//getDeclaredField可以获取各种访问控制符的域
		
		//设置通过反射访问该Field时取消访问权限检查,如果不设置,无法通过下面的set方法为其赋值。
		field1.setAccessible(true);
		field1.set(obj, "张三");

		System.out.println(field1.get(obj));//输出结果:张三
	}
}

猜你喜欢

转载自huangqiqing123.iteye.com/blog/1407988