据我所知,在Java中,当一个类使用public访问修饰符时,无法像C#中的internal protected那样为类成员添加internal package protected访问修饰符。您是否知道任何方法或设计模式来解决这个问题?为什么Java没有语法支持实现这一点?(或者为什么C#有?)
protected
修饰符和类的 package private
。它们允许来自相同包以及继承类的访问。internal
,提示客户不要直接使用这个包中的类。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 :)");
}
}
}
}