Accessing Package Visibility Features In Other Packages
Java Programming Tricks
Accessing package visibility features in other packages:
The deafult visibility attribute for fields and methods is package
visibility
class X
{ void f(); // can be accessed by all methocis in the same package
int n; // can be accessed by all methods in. the same package
}
If a field or method isn't tagged as public Of private, then it can
be accessed by the methods of all classes in the same package. That
sounds secure, but it is not, since any programmer can add more
classes to any package.
Tip
Add a class to an existing package if you need to access package
visibility fields. Here is an example.
public class Window extends Container
{ String warningString; // Privat !!
static final int OPENED = 0x01;
int state;
transient WindowListener windowListener;
}
The warning string is displayed on windows spawned by applets. It says
something scary like:
"Unauthenticated applet window"
Prefer a friendlier greeting? Make a class
package java.awt;
public class GreetingSetter
{ public static void changeNaming(Window w, String s)
{ w.warningString = s;
}
}
Compile, and add the GreetingSetter. class into the directory
\jdk\lib\ java\awt, or any other directory java\awt off the class path.
Then add the following in your window constructor:
GreetingSetter.changeWarning(this, "Trust me!");
Note
This attack does not actually work for applets, because the applet class
loader checks whether you add new classes to system packages. But as applet
class loaders become more selective, granting different access privileges
depending on trust levels, this could turn into a security hole.
As a general rule, never use package access. In the case of the warningString, no other method actually accesses that field. The author merely forgot to tag it as private.