1. 程式人生 > >java反射機制——獲取位元組碼對應類中的欄位

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

}