Java中的Internal Package Protected访问修饰符

3
据我所知,在Java中,当一个类使用public访问修饰符时,无法像C#中的internal protected那样为类成员添加internal package protected访问修饰符。您是否知道任何方法或设计模式来解决这个问题?为什么Java没有语法支持实现这一点?(或者为什么C#有?)

Jigsaw 项目 http://openjdk.java.net/projects/jigsaw/ 可能会根据使用情况提供一些缓解。 - Fuhrmanator
1个回答

3
在Java中,最接近的是类成员的 plain protected 修饰符和类的 package private。它们允许来自相同包以及继承类的访问。
实际上,你会发现Java包的命名方式像是 internal,提示客户不要直接使用这个包中的类。
更新:
没有办法在编译时强制执行此类限制。但是在运行时,您有各种选项,例如使用Java安全性、反射、分析堆栈跟踪。但是您应该在每种情况下评估每种解决方案的利弊。
只是为了好玩,可以尝试以下内容(我怀疑这在真实项目中没有用处,也不确定它是否与生成字节代码的代理或其他奇特的用例兼容):
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 :)");
             }
         }
     }
}

是的,那是对的。但是如果我想要创建一个公共类,只有内部受保护的成员,我该怎么办?我会明确我的问题,因为我看到它可能会有歧义。 - pt12lol

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接