Page 3 of 3
Before using this approach, you should consider a number of its details and implications:
ExampleCallee depends on ValidCaller's cooperation: The ExampleCallee class depends on ValidCaller cooperation in enforcing the scoping restrictions. ValidCaller can cheat by making the Key class public, or by handing out references to Key objects. However, even with standard scoping, legal callers can cheat. Our approach assumes cooperation between the valid
caller classes and the callee, just as standard Java scoping does.Key object is a static inner class: This means that both static and nonstatic member functions in the ValidCaller class have access to sampleMethod. To prevent static methods from calling sampleMethod, make the Key object nonstatic.Key object is a private inner class: Making Key private means that subclasses of ValidCaller cannot construct Key objects. Making Key a protected inner class grants access to child classes as well.Key need not be an inner class: Key could be a package-scope class if your intent is to grant any class in a package access to sampleMethod().Key must not be anonymous: The Java language does not specify a naming convention for anonymous inner classes, and different compilers generate different
names for anonymous inner classes. Because of this, you should name the Key class.Standard Java scoping is sufficient for most projects. For large projects, however, you occasionally need to construct very specific scoping relationships. The approach to doing so presented in this article uses only the standard JDK 1.1 language constructs, and does not require any extensions to the Java language. This approach does add some complexity, though, so you should use it with caution. If you find yourself using this technique often, you need to reconsider your design.