开发者

How to use Java access modifier properly in library development

I'm developing a library which the other programmer will import and use it for their purposes.

I'm confused about the objective of Java access modifier.

The problem is that I have classes below

  • ClassA in package org.mylibrary
  • ClassB in package org.mylibrary.internal

ClassA needs to resolve ClassB so ClassB need to be public class.

However, from library user view, I don't intend ClassB to be visible outside my library. Because it shouldn't be and don't need to be initiated by the user.

I think of moving ClassB to package org.mylibrary and make it package-private class.

If I move it to the same package, it would be a开发者_开发知识库 mess and difficult to organize because I have many classes in this scenario so there will be many .java files in a big one package.

Normally I put the classes in packages grouped by category or layer and I think it's easy to organize.

How do I do this? How do people handle this problem?


It is difficult to give concrete advice since you give so little info about the roles of and relationship between ClassA and ClassB. However, one general solution (which is almost always used as part of eliminating dependencies) is to hide ClassB behind an interface. Then ClassA uses only that interface, so it is not anymore directly dependent on ClassB. ClassB can be made package private, its instances produced by e.g. a factory, or dependency injected into ClassA.


Assuming ClassB is a test package with unit tests:

Why does ClassB need to use it. Normally test classes use the regular classes, not vice versa.

In general, the recommendation for test classes is to put them into the same package as the regular classes, but maintain the .java files in a parallel directory hierarchy (i.e. you have src/org/mycompany/MyClass.java , and test-src/org/mycompany/MyClassTest.java ). That way, to Java both are in the same package and can access each other, and for release builds you just don't compile the test classes (or don't even check them out) - that way everything is nicely separate.

If this does not apply in your case, maybe you could edit your question with more detail?


It would be a mess and difficult to organize because I have many classes in this scenario.

Do you mean that the java file look messy? You can split the internal classes in a different .java file.

ClassA.java

package org.application;

public class ClassA {
}

Internal.java

package org.application;

class ClassB {
}

class SomeOtherInternalClass {
}

Hope this helps.


i think i understand your question, and the answer is that there is no way to do that in java up to now!

there are some tricky ways but they invovle dirt coding.

look here

http://openide.netbeans.org/tutorial/api-design.html#design.less.friend

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜