您的位置:首页 > 其它

利用反射直接访问类中的私有变量

2012-01-02 22:41 417 查看
package reflection;

import java.lang.reflect.Field;

import java.lang.reflect.InvocationTargetException;

import java.lang.reflect.Method;

public class testMain {

/**

* @param args

*/

public static void main(String[] args) {

ClassLoader loader = testMain.class.getClassLoader();

try {

Class c = loader.loadClass("reflection.Empolyee");

//Empolyee类中包含私有变量name,默认值为a;包含getName()方法

Empolyee e = (Empolyee)c.newInstance();

Field[] fields = c.getDeclaredFields();

//获取名为name的属性

Field f = c.getDeclaredField("name");

//取消访问权限检查

f.setAccessible(true);

//将reflection.Empolyee类型的实例e中的name属性值设为123

f.set(e, "123");

//获取名为getName的方法,没有参数

Method m = c.getMethod("getName", null);

//调用getName方法

System.out.println(m.invoke(e, null));

} catch (ClassNotFoundException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (SecurityException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (IllegalArgumentException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (IllegalAccessException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (InstantiationException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (NoSuchFieldException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (NoSuchMethodException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (InvocationTargetException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: