java反射机制——获取字节码对应类中的字段

package cn.itcast.reflect.demo;

import java.lang.reflect.Field;

public class ReflectDemo3 {

	public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, SecurityException, InstantiationException, IllegalAccessException {
		
		//字段的访问
		
		getfieldDemo();
	}

	public static void getfieldDemo() throws ClassNotFoundException, NoSuchFieldException, SecurityException, InstantiationException, IllegalAccessException {
		
		String classname="cn.itcast.bean.demo.Person";
		Class c=Class.forName(classname);
		
		Field field=c.getDeclaredField("age");//能获取包含私有的字段
		field.setAccessible(true);//对私有字段的访问取消权限检查,暴力访问
		Object obj=c.newInstance();
		
		field.set(obj, 50);
		Object o=field.get(obj);
		System.out.println(o);
	}

}

猜你喜欢

转载自blog.csdn.net/TDOA1024/article/details/82919459