Violating Java's privacy
Posted by F Tue, 20 Feb 2007 03:49:00 GMT
I found myself in the need to invoke a private method of a Java class that was out of my control. I really needed it.
So, I went ahead and violated the method’s privacy declaration via
reflection. You can (under certain circumstances) invoke methods which
are declared as private using the Reflection APIs (java.lang.reflect).
But before using reflection, I created two classes:
class A {
public String method1() {
return "Hello World!";
}
}
class B {
public static void main(String[] args) {
A a = new A();
System.out.println(a.method1());
}
}
They compiled, and java B said “Hello World!” as expected.
Then, I made A’s method private and recompiled A. And I run java B again. Nothing changed. It just worked again.
That cannot be right. This would mean you can handcraft a class with the
same name and methods as the original one but making everything
public. Then you could use this class only at compilation time,
allowing your code to call any method. (Or, one could modify
the Java compiler to ignore access declarations altogether).