2015-09-07 11:44:36 -06:00
|
|
|
// typeinfo/HiddenImplementation.java
|
2015-12-15 11:47:04 -08:00
|
|
|
// (c)2016 MindView LLC: see Copyright.txt
|
2015-11-15 15:51:35 -08:00
|
|
|
// We make no guarantees that this code is fit for any purpose.
|
2016-09-23 13:23:35 -06:00
|
|
|
// Visit http://OnJava8.com for more book information.
|
2016-01-25 18:05:55 -08:00
|
|
|
// Sneaking around package hiding
|
2015-06-15 17:47:35 -07:00
|
|
|
import typeinfo.interfacea.*;
|
|
|
|
import typeinfo.packageaccess.*;
|
|
|
|
import java.lang.reflect.*;
|
|
|
|
|
|
|
|
public class HiddenImplementation {
|
2016-01-25 18:05:55 -08:00
|
|
|
public static void
|
|
|
|
main(String[] args) throws Exception {
|
2015-06-15 17:47:35 -07:00
|
|
|
A a = HiddenC.makeA();
|
|
|
|
a.f();
|
|
|
|
System.out.println(a.getClass().getName());
|
|
|
|
// Compile error: cannot find symbol 'C':
|
|
|
|
/* if(a instanceof C) {
|
|
|
|
C c = (C)a;
|
|
|
|
c.g();
|
|
|
|
} */
|
|
|
|
// Oops! Reflection still allows us to call g():
|
|
|
|
callHiddenMethod(a, "g");
|
|
|
|
// And even methods that are less accessible!
|
|
|
|
callHiddenMethod(a, "u");
|
|
|
|
callHiddenMethod(a, "v");
|
|
|
|
callHiddenMethod(a, "w");
|
|
|
|
}
|
2016-01-25 18:05:55 -08:00
|
|
|
static void
|
|
|
|
callHiddenMethod(Object a, String methodName)
|
2015-06-15 17:47:35 -07:00
|
|
|
throws Exception {
|
|
|
|
Method g = a.getClass().getDeclaredMethod(methodName);
|
|
|
|
g.setAccessible(true);
|
|
|
|
g.invoke(a);
|
|
|
|
}
|
2015-09-07 11:44:36 -06:00
|
|
|
}
|
|
|
|
/* Output:
|
2015-06-15 17:47:35 -07:00
|
|
|
public C.f()
|
|
|
|
typeinfo.packageaccess.C
|
|
|
|
public C.g()
|
|
|
|
package C.u()
|
|
|
|
protected C.v()
|
|
|
|
private C.w()
|
2015-09-07 11:44:36 -06:00
|
|
|
*/
|