public class Test1 {
public static void main(String[] args) {
try {
Class clazz = Class.forName(“Reflect.Student”);
//通过包名.类名的字符串,调用class. forName方法获取指定类的class实例
//反射创建一个对象
Constructor con = clazz.getConstructor();
Student stu = (Student)con.newInstance();
// Field f2 = clazz.getField(“school”);获取名称为schoo1的公有属性
Field f = clazz.getDeclaredField(“school”);//获取名称为schoo1的属性
f.set(stu,“第三中学”);//对gtu对象的schoo1属性设置值"第三中学"
String school =(String)f.get(stu); //获取stu对象的school属性的值
System.out.println(school);
Field f2 = clazz.getDeclaredField("privateFild");
f2.setAccessible(true);//解除私有封装
f2.set(stu,"测试私有属性");
System.out.println(f2.get(stu));
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}