使用java反射,获取类的私有属性,调用类的私有方法
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class PrivateObject {
private String privateString = null;
public PrivateObject(String privateString) {
this.privateString = privateString;
}
private String getPrivateString() {
System.out.println("----------调用了私有方法-------------");
return "-----私有方法------";
}
public static void main(String[] args) throws Exception {
callPrivateMethod();
}
private static void callPrivateMethod() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
PrivateObject privateObject = new PrivateObject("The Private Value");
Method privateStringMethod = PrivateObject.class.getDeclaredMethod("getPrivateString", null);
privateStringMethod.setAccessible(true);
String returnValue = (String) privateStringMethod.invoke(privateObject, null);
System.out.println("returnValue = " + returnValue);
}
private static void getPrivateAttribure() throws NoSuchFieldException, IllegalAccessException {
PrivateObject privateObject = new PrivateObject("The Private Value");
Field privateStringField = PrivateObject.class.getDeclaredField("privateString");
privateStringField.setAccessible(true);
String fieldValue = (String) privateStringField.get(privateObject);
System.out.println("fieldValue = " + fieldValue);
}
}