反射使用成员变量 ,并赋值,保函反射的使用

package Fanshe;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

//需求:通过反射实现操作
//Student s=new Student()
//s.name="林青霞";
//s.age=30; sout。。。。。。
public class Fanshedeom4 {
public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
//得到class对象
Class<?> clss = Class.forName("Fanshe.Student");
//获取所以成员变量,遍历
Field[] allfields = clss.getDeclaredFields();
for (Field allfield : allfields) {
System.out.println(allfield);
}
//得到成员变量
Field name = clss.getDeclaredField("name");
Field age = clss.getDeclaredField("age");
//获取无参构造
Constructor<?> stu = clss.getConstructor();
//创建对象
Object obj = stu.newInstance();
name.set(obj,"林青霞");
// age为私有变量,使用时需要使用暴力反射
age.setAccessible(true);
age.set(obj,20);
System.out.println(obj);

}
}
posted @ 2021-11-17 16:57  java小寇  阅读(58)  评论(0)    收藏  举报