开发者

JAR-Level (Assembly-Level) Class Scoping in Java

开发者 https://www.devze.com 2023-04-08 07:47 出处:网络
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).

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开发者_StackOverflow中文版 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.


Java has no concept of library-level scoping. Make the classes public or use a factory.


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

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号