Search code examples
javadesign-patternssyntaxprotectedpackage-private

Internal Package Protected access modifier in Java


As far as I know, it is impossible classical way to add for a class member in Java internal package protected access modifier (such as internal protected in C#) when its class has public access modifier. Do you know any way or design pattern to do this?

Why there is no syntax support to do this in Java? (or why it is in C#?)


Solution

  • In Java the closest would be the plain protected modifier for class members and package private for classes. They allow access from the same package as well as from the inheriting classes.

    In practice you will find Java packages are named like internal hinting the clients that they shouldn't use the classes in this package directly.

    UPD

    There's no way to force such kind of restriction at compile time. But at runtime you have various options like using Java Security, reflection, analyzing stack trace. But you should evaluate the pros and cons of each solution in each context.

    Just for fun you could try this (I doubt this is useful in real world projects, also not sure how nice this would play with bytecode-generating proxies or maybe other exotic use cases):

    public class Test {
         public void protectedInternal() {
             // If this method is not called from an inherited class.
             if (getClass() == Test.class) {
                 StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
                 StackTraceElement e = stackTrace[2]; // Corresponds to the caller stack frame.
                 // Check the caller is from the allowed package.
                 if (!e.getClassName().startsWith("my.package.")) {
                     throw new SecurityException("Sorry, this method is kind of protected internal :)");
                 }
             }
         }
    }