使用反射机制,需要知道这个方法名(摘自think in java)
package access.intefacea;
public interface A {
void f();
}
package access.pmethod;
import access.intefacea.*;
class C implements A{
public void f() {
System.out.println("public C.f()");
}
public void g(){
System.out.println("public C.g()");
}
void u(){
System.out.println("package C.u()");
}
protected void v(){
System.out.println("protected C.v()");
}
private void w(){
System.out.println("private C.w()");
}
}
public class HiddenC {
public static A makeA(){
return new C();
}
}
package access.test;
import java.lang.reflect.Method;
import access.intefacea.*;
import access.pmethod.*;
public class HiddenImplementation {
public static void main(String[] args) throws Exception {
A a = HiddenC.makeA();
a.f();
System.out.println(a.getClass().getName());
//在这里C是不可见的
/*
if(a instanceof C){
C c = (C)a;
c.g();
}
*/
callHiddenMethod(a, "g");
callHiddenMethod(a, "u"); //访问包访问权限的方法
callHiddenMethod(a, "v"); //访问proctected权限的方法
callHiddenMethod(a, "w"); //访问私有权限方法
//如果不知道方法名,可以通过javap -private C来获得
}
static void callHiddenMethod(Object a, String methodName) throws Exception{
Method g = a.getClass().getDeclaredMethod(methodName);
g.setAccessible(true); //设置为不检查权限
g.invoke(a);
}
}