反射获取私有属性
作者:互联网
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);
}
}
标签:反射,私有,studObject,Student,filed,fanshe,属性,Class,class1 来源: https://blog.csdn.net/weixin_42591732/article/details/94052992