[英]Java Class Protection
I suspect the answer is no, but I want to check.我怀疑答案是否定的,但我想检查一下。 If I have this structure in a Java application:
如果我在 Java 应用程序中有这个结构:
-package
-ClassA
-subpackage
-ClassB
-subsubpackage
-ClassC
I want package.subpackage.ClassB to have access to package.subpackage.subsubpackage.ClassC, but I don't want package.ClassA to have access to package.subpackage.subsubpackage.ClassC. I want package.subpackage.ClassB to have access to package.subpackage.subsubpackage.ClassC, but I don't want package.ClassA to have access to package.subpackage.subsubpackage.ClassC. Is there any way to enforce this?
有什么办法可以强制执行吗?
No, the only access modifiers are:不,唯一的访问修饰符是:
public
- global access public
- 全球访问protected
- package and subclass access protected
- package 和子类访问private
- class access only private
- 仅限 class 访问protected
and package-private doesn't recursively grant access to subpackages. protected
和 package-private 不会递归地授予对子包的访问权限。 In short, subpackages don't really have any relationship with their parent package except for the fact that they share the same name prefix.简而言之,子包与其父 package 没有任何关系,只是它们共享相同的名称前缀。
Here is a Java Specification Request that (I believe) deals with this issue: http://jcp.org/en/jsr/detail?id=294这是(我相信)处理此问题的 Java 规范请求: http://jcp.org/en/jsr/detail?id=294
This was supposed to be implemented in the just recently released Java 7, but apparently has been forgotten.这应该在最近发布的 Java 7 中实现,但显然已经被遗忘了。
The only way that you can get this to work is through the use of inner classes .让这个工作的唯一方法是使用 内部类。 And, honestly, if that doesn't work then maybe you should be asking, "What is so important about C that A shouldn't be able to instantiate it but B and at least one other class can?"
而且,老实说,如果这不起作用,那么也许您应该问:“C 有什么重要的,以至于 A 不能实例化它,但 B 和至少一个其他 class 可以?”
No, there isn't.不,没有。 A package name is not an hierarchical construct If we have a class
package 名称不是层次结构如果我们有 class
foo.bar.Application
then bar
is not a child-package of foo
.那么
bar
不是foo
的子包。 The package is foo.bar
and there is no relation between foo
and foo.bar
, they are totally different packages (namespaces). package 是
foo.bar
并且foo
和foo.bar
之间没有关系,它们是完全不同的包(命名空间)。
Making ClassC as an internal class for ClassB may solve your task.将 ClassC 作为 ClassB 的内部 class 可以解决您的任务。
No. The package hierarchy in Java has no effect on package visibility.不会。Java 中的 package 层次结构对 package 可见性没有影响。
Things are either totally public or package-private.事情要么是完全公开的,要么是包私有的。
There is no such thing as a "friend" package or a "parent" package here.这里没有“朋友”package 或“父母”package 这样的东西。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.