1. 程式人生 > 其它 >反射使用成員變數 ,並賦值,保函反射的使用

反射使用成員變數 ,並賦值,保函反射的使用

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);

}
}