Java中的JAR级(组装级)类作用域 [英] JAR-Level (Assembly-Level) Class Scoping in Java

查看:56
本文介绍了Java中的JAR级(组装级)类作用域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#中,如果我希望某个类对该程序集(DLL)中的任何类可见,则只需将其范围限定为internal(这是默认设置).

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).

如何在Java中执行此操作?在Java中,我注意到默认/内部范围是程序包级别,而不是 JAR级别.这对我来说是个问题,因为我有一个库,其中包含多个具有不同职责(视图,控制器等)的子包,因此不能将它们放在同一包中.

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.

作为一个例子,我有两个类,例如com.stackoverflow.main.first.Onecom.stackoverflow.main.second.Two,这两个类都应该能够彼此实例化.

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.

编辑:我不希望该类为public,并且对于引用它的任何人都是可见的.这是内部类 only .我正在创建一个供消费的API,对我来说最重要的是我的JAR的消费者可以看到哪些类.

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.

推荐答案

要完成所需的工作,您必须使用某种工厂模式的组合来创建要公开的类,并将私有类包保留为私有.通常,我是这样做的:

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:

  1. 在诸如com.foo.bar la public interface Foo {}
  2. 之类的包中为API创建公共接口
  3. 创建一个工厂类,该类公开一个创建方法la: public class FooFactory{ public Foo buildFoo(){ return new FooImpl(); }
  4. 将FooImpl创建为包私有类-class FooImpl implements Foo{}
  5. 说明正确用法的文档包.
  1. create the public interface for the API in a package like com.foo.bar a la public interface Foo {}
  2. create a factory class that exposes a create method a la: public class FooFactory{ public Foo buildFoo(){ return new FooImpl(); }
  3. create FooImpl as a package private class - class FooImpl implements Foo{}
  4. Document package to indicate proper usage.

这不是完美的,但是直到有关模块作用域的JSR进展,它才可能是您在Java中获得的最接近的产品.如果要确保FooImpl不会被不适当地扩展,请确保将其标记为final.

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.

这篇关于Java中的JAR级(组装级)类作用域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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