JAVAパッケージ学習ノート2---反射破壊パッケージ

859 ワード

JAvaには、パッケージを破壊できるメカニズムがあります.反射と呼ばれますが、(反射呼び出しクラスのプライベートメソッドを通じて)どのように使用しますか?
次のケースコードを見てください
package dotclassUse;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import Test.Test;
public class TestdotClassUse {
public static void main(String[] args) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException{
Class a = Test.class;//  test class  ,   Class   
Method[] methods = a.getDeclaredMethods();//                 
for (Method method : methods) {
if(method.getName().equals("test1"))
{
method.setAccessible(true);
method.invoke(new Test());
}
}
}
}
package Test;
public class Test {
private int a;
public Test(){}
private void test1(){System.out.println("    ");}
public void test2(){System.out.println("    ");}
}