在Java中实现接口时降低可见性 [英] Reduce visibility when implementing interface in Java

查看:742
本文介绍了在Java中实现接口时降低可见性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想设计类A实现接口C并降低方法的可见性(在C中声明)以使其从外部世界安全,使得在A类中实现的接口中的一个方法成为私有的(降低了可见性) A)级。出于安全原因,我必须这样做,我该怎么做,是否有解决方法。我们知道默认情况下,界面有公共成员。但我没有选择,有人可以帮助我。提前致谢。

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). I have to do this for security reason, how can I do this, is there a workaround. We do know that by default, the interface has public members. But there is no option for me, can someone help me. Thanks in advance.

-
因此,没有办法从接口获得类实现方法并将其设为私有。并且所有实现任何接口方法的类都将始终具有公共方法?

-- So , there is no way, to have a class implement method from interface and make it private. And all classes that implement any interface's method will always have public methods?

推荐答案

不,您无法降低其可见性接口中的方法。如果有人写道,你会发生什么:

No, you can't reduce the visibility of a method in an interface. What would you expect to happen if someone wrote:

C foo = new A();
foo.methodDeclaredPrivateInA();

?就编译器而言,所有引用 C 实现的内容都有权调用其中的任何方法 - 这就是Liskov的替换原则。

? As far as the compiler is concerned, everything with a reference to an implementation of C has the right to call any methods within it - that's what Liskov's Substitution Principle is all about.

如果你不想实现整个公共接口,不要实现它 - 或者如果你绝对必须抛出异常。

If you don't want to implement the whole of a public interface, don't implement it - or throw exceptions if you absolutely must.

还值得注意的是,源代码中提供的可访问性很少是一个很好的安全性度量。如果您的类在VM中运行,而VM又可以确定自己的权限,那么任何人都可以通过反射使成员可见。

It's also worth noting that the accessibility provided in source code is rarely a good security measure. If your class is running in a VM which in turn gets to determine its own permissions, anyone can make members visible via reflection.

这篇关于在Java中实现接口时降低可见性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆