Java 中的 JAR 级(汇编级)类范围
在 C# 中,如果我希望某个类对该程序集 (DLL) 中的任何类都可见,我只需将其范围设置为 internal
(这是默认设置)。
如何在 Java 中执行此操作?在 Java 中,我注意到默认/内部作用域是包级别,而不是JAR 级别。对我来说是一个问题,因为我有一个库,它有几个具有不同职责(视图、控制器等)的子包,并且不能将它们放在同一个包中。
例如,我有两个类,例如 com.stackoverflow.main.first.One 和 com.stackoverflow.main.second.Two,它们都应该能够互相实例化。
编辑:我不希望该类是公共
并且对引用它的任何人都可见。它只是一个内部类。仅。我正在创建一个用于消费的 API,对我来说最重要的是我的 JAR 的消费者可以看到哪些类。
In C#, if I want a class to be visible to any class within that assembly (DLL), I simply scope it as internal
(which is the default).
How can I do this in Java? In Java, I've noticed the default/internal scoping is package level, not JAR level. This is a problem for me, since I have a library that has several sub-packages with different responsibilities (view, controller, etc.) and can't put them in the same package.
As an example, I have two classes like com.stackoverflow.main.first.One
and com.stackoverflow.main.second.Two
, both of which should be able to instantiate each other.
Edit: I don't want the class to be public
and visible from anyone who references it. It's an internal class only. I'm creating an API for consumption, and of primary importance to me is which classes can be seen by consumers of my JAR.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Java 没有库级作用域的概念。将类公开或使用工厂。
Java has no concept of library-level scoping. Make the classes public or use a factory.
为了实现您想要的目标,您必须使用工厂模式的某种组合来创建您想要公开的类,并将私有类包保留为私有。通常,我会这样做:
com.foo.bar
等包中创建 API 的公共接口,并在public interface Foo {}
中公共类 FooFactory{
公共 Foo buildFoo(){ 返回 new FooImpl(); }
class FooImpl 实现 Foo{}
它并不完美,但在有关模块作用域的 JSR 取得进展之前,它可能是您在 java 中可以获得的最接近的结果。如果您想确保 FooImpl 不会被不当扩展,请确保将其标记为 Final。
To accomplish what you want, you'll have to use some mix of a factory pattern to create the classes you want to expose and leave the private classes package private. Usually, I've done this:
com.foo.bar
a lapublic interface Foo {}
public class FooFactory{
public Foo buildFoo(){ return new FooImpl(); }
class FooImpl implements Foo{}
It's not perfect, but until the JSR about module scoping progresses, it's probably the closest you can get in java. If you want to ensure that FooImpl doesn't get inappropriately extended, be sure it is marked final.
听起来很简单,因为您必须使用公共访问修饰符。
sounds as simple as you have to use the public access modifier.