Java之通过Class字节码对象获取一个类里面的字段值

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_38225558/article/details/82730170
/**
 * 字节码对象获取一个类里面的字段值
 * @author 郑清
 */
public class Demo {

	public static void main(String[] args) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchMethodException {
		test();
	}
	
	public static void test() throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchMethodException{
		//获取类的字节码对象
		Class cla = Student.class;
		
		//获取无参公共(public)的构造方法 创建对象
		Object obj = cla.getConstructor().newInstance();
		//System.out.println(obj);//Student对象
		
		//获取字段name
		Field field = cla.getField("name");
		
		//注意:字段值需要设置到某个对象上面去
		field.set(obj, "String类型name值");
		System.out.println(field.get(obj));
		
		Student stu = (Student)obj;
		System.out.println(stu.name);
	}

}

class Student {
	
	public String name;
	
	public Student() {}
	
}

运行结果图:

猜你喜欢

转载自blog.csdn.net/qq_38225558/article/details/82730170