![](/img/trans.png)
[英]Reducing visibility of the java interface when implementing it in an abstract class
[英]Reduce visibility when implementing interface in Java
I would like to design class A implements interface C and reduce the visibility of a method (declared in C)to make it secure from outer world, make one of the methods in interface implemented in class A as private (reducing visibility in class A) . 出于安全原因,我必须这样做,我该怎么做,是否有解决方法。 我们知道,默认情况下,接口有公共成员。 但是我没有选择,有人可以帮助我。 提前致谢。
-- 所以,没有办法让 class 从接口实现方法并使其私有。 并且所有实现任何接口方法的类都将始终具有公共方法?
不,您不能降低接口中方法的可见性。 如果有人写道:你会期望发生什么:
C foo = new A();
foo.methodDeclaredPrivateInA();
? 就编译器而言,引用C
实现的所有内容都有权调用其中的任何方法 - 这就是 Liskov 的替换原则的全部内容。
如果您不想实现整个公共接口,请不要实现它 - 或在绝对必须时抛出异常。
还值得注意的是,源代码中提供的可访问性很少是一种好的安全措施。 如果您的 class 在虚拟机中运行,而虚拟机又可以确定自己的权限,则任何人都可以通过反射使成员可见。
不能降低 Java 中接口方法的可见性。 您可以通过抛出java.lang.UnsupportedOperationException
来实现该方法吗?
这种方法对我有用。 任何添加到 PrivateInterface 的新 function 都会破坏 PublicSampleClass
private interface PrivateInterface {
void fooBar();
}
public class PublicSampleClass {
private final listenerInterface = new PrivateInterface {
public void fooBar() {
PublicSampleClass.this.fooBar();
}
};
protected void fooBar() {
// Non public implementation
}
}
你不能减少可见性,因为你可以写一些类似的东西
C newC = new A();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.