package com.day14.fanshe;
import java.lang.reflect.Field;
public class Test {
public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, SecurityException,
InstantiationException, IllegalAccessException {
// TODO Auto-generated method stub
// Student student = new Student();
// Class<? extends Student> class1=student.getClass();
// class1.getName();
// System.out.println(class1.getName());
//
// Class<? extends Student> class1=new Student().getClass();
//
// try {
// Class<?> class1=Class.forName("com.day14.fanshe.Student");
//
// Beans bean=(Beans) class1.newInstance();
//
// } catch (Exception e) {
// // TODO: handle exception
// }
// 获取字节码对象
Class class1 = Class.forName("com.day14.fanshe.Student");
// 创建学生对象
Object studObject = class1.newInstance();
// 暴力反射获取属性
Field filed = class1.getDeclaredField("name");
// 设置反射时取消Java的访问检查,暴力访问
filed.setAccessible(true);
filed.set(studObject, "哈哈哈");
Object nameObject = filed.get(studObject);
System.out.println(nameObject);
}
}
反射获取私有属性
最新推荐文章于 2024-08-04 07:57:55 发布