如何使用反射访问类的private域和方法

 

如何使用反射访问类的private域和方法?非常简单,由于Field和Method均继承AccessibleObject,只需要调用AccessibleObject的public void setAccessible(boolean flag) throws SecurityException 方法设置为setAccessible(true)即可。具体见下列代码

 

 

import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class ReflectTest {

	public static void main(String[] args) throws Exception {

		PrivateClass pri = (PrivateClass) Class.forName("PrivateClass")
				.newInstance();
		Field field = Class.forName("PrivateClass")
				.getDeclaredField("priField");
		try {
			field.set(pri, "youareprivate?");
			pri.getPriField();
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}

		field.setAccessible(true);
		field.set(pri, "youareprivate?");
		pri.getPriField();

		Method method = Class.forName("PrivateClass").getDeclaredMethod(
				"priMethod", new Class[] {});
		try {
			method.invoke(pri, new Object[] {});
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}

		method.setAccessible(true);
		method.invoke(pri, new Object[] {});

	}
}

class PrivateClass {
	private String priField = "priField ";

	public void getPriField() {
		System.out.println(" the value of priField is " + priField);
	}

	private void priMethod() {
		System.out.println("call the private method!");
	}
}

 

 

结果:

Class ReflectTest can not access a member of class PrivateClass with modifiers "private"
 the value of priField is youareprivate?
Class ReflectTest can not access a member of class PrivateClass with modifiers "private"
call the private method!
 

你可能感兴趣的:(Access)