开发者

Providing other Packages accesibility to "no-modifier" methods

There is a class named

public Class Foo{

   public something(){
   ...}

   Foo(){
   ...}
}

Now as the class is public it can be accessed by anyone but it's constructor is only available to its local package, But is there a way to provide the constructor to any other package

The issue is that Its already quite a big code开发者_运维知识库 I'm working on, and don't want the constructor available to the public, but unfortunately someone already has used used it outside the package (the constructor was public before)


I think what you are looking for is something equivalent to the friend operator from C++. And Java doesn't have this (for good reason).

Depending on how bad this is, you could mark the public constructor as deprecated, and switch to using a factory method for your package-only use. Then change the constructor to package private in another couple of releases

Long and short: once you've released an API to the public, you've either got to support it, or break their builds.


Visibility in Java is package-based, and it is an all-or-nothing decision, e.g. you don't have anything like declaring a "friend class" in C++. So I'm afraid there is no way to do what you want, except waiting for project Jigsaw (looks like it's in Java8).

One thing you could do is to keep the constructor public, but to annotate it as @Deprecated, and to comment that it shouldn't be used outside of the package.

Except that there is only the hard solution to remove the public, let it break, so other people need to fix their code. You won't make new friends with this action, but it's hard to get the genie back in the bottle once it is out. Still better now than later - think of the public constructors of primitive wrappers like Integer(int), where Sun got it very wrong, and couldn't take it back later.


No such feature. I would try to locate existing places where constructor is used and fix them. (if there're not too many)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜