Class类
成员方法
public Filed getFiled(String name);<br /> 返回一个Filed对象,仅公共成员变量<br /> public Filed getDeclaredFiled(String name);<br /> 返回一个Filed对象,可获取私有成员变量<br /> public Filed[] getDeclaredFileds();<br /> 返回此类所有(含私有)变量的数组
Method类
概述
属于java.base模块下的java.lang.reflect包下的类
成员方法
public void setAccessible(boolean flag); 是否开启暴力反射(true:开启)<br /> public void set (Object obj, Object value); 设置obj对象的指定属性值为value
案例
public class ReflectDemo3 {public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchFieldException {//需求:通过反射获取成员变量并使用//1.获取Student类的字节码文件对象Class clazz = Class.forName("Note.Student");//2.通过字节码文件对象获取构造器对象,然后创建学生类对象/* Constructor con = clazz.getConstructor();Student stu = (Student) con.newInstance();*/Student stu = (Student) clazz.getConstructor().newInstance();//3.设置学生对象是各个属性值//3.1设置姓名Field filed1 = clazz.getDeclaredField("name");filed1.setAccessible(true);filed1.set(stu,"zhagsan");//3.2设置年龄Field filed2 = clazz.getDeclaredField("id");filed2.setAccessible(true);filed2.set(stu,30);//4.打印学生对象System.out.println(stu);}}
