廢話不多說直接貼代碼,代碼中有注釋,如下:
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class Test {
@SuppressWarnings(“unused”)
class Test1{
//私有屬性
private String color = “blue”;
//無參數的私有方法使用私有屬性
private void queryColor(){
System.out.println(color);
}
//一個參數的私有方法
private void privateTest1(String param1) {
System.out.println(“>>>>>>” + param1 + “>>>>>>>>>” + color +”>>>>>>>>>>”);
}
//兩個參數的私有方法
private void privateTest2(String param1,String param2) {
System.out.println(“>>>>>>” + param1 + “>>>>>>>>>”+ param2 + “>>>>>>>>”);
}
}
public static void main(String[] args) {
try {
Test test = new Test();
Test1 test1 = test.new Test1();
//擷取内部類的私有屬性
Field colorField = Test1.class.getDeclaredField(“color”);
//設定為true表示可以通路private修飾的私有屬性
colorField.setAccessible(true);
System.out.println(colorField);
//color的值改為red
colorField.set(test1, “red”);
//擷取内部類的私有方法,無參數的
Method method = Test1.class.getDeclaredMethod(“queryColor”);
//設定為true表示可以通路private修飾的私有方法
method.setAccessible(true);
System.out.println(method);
//用來執行指定對象的方法,無參數的
method.invoke(test1);
//擷取内部類的私有方法,一個參數的
Method method1 = Test1.class.getDeclaredMethod(“privateTest1”,String.class);
//設定為true表示可以通路private修飾的私有方法
method1.setAccessible(true);
System.out.println(method1);
//用來執行指定對象的方法,前面test1是對象,後面的是一個參數
method1.invoke(test1,”我調用了你的私有方法!!!”);
//擷取内部類的私有方法,兩個參數的
Method method2 = Test1.class.getDeclaredMethod(“privateTest2”,String.class,String.class);
//設定為true表示可以通路private修飾的私有方法
method2.setAccessible(true);
System.out.println(method2);
//用來執行指定對象的方法,前面test1是對象,後面的是兩個參數
method2.invoke(test1, “用我的參數1″,”用我的參數2”);
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
運作後列印,如下:
