I have 2 Java packages, A & B. Let's say that some classes in package B want to use some classes in package A however, when a developer comes along and develops package C (or, say, application C), he/she will use my package B but I do not want him/her to be able to use the classes in A that B is using. That is to say, I want my classes in package A to be package private so that they are hidden from the application developer. However, I do want my own package B to be able to access those classes which are package private. Can this be done in Java? Do I basically just need to bite the bullet and make the classes public and just hope that the user doesn't try to use them? Or, do I need to replicate the classes that are in A inside of B?
My preference would be something that is not hack-y (i.e. I don't want to use reflection). Help?
You can do it with JDK 8 and its Project Jigsaw. You might want to give a look to Project Jigsaw Quickstart Guide.
Unfortunately, Jigsaw is part of the JDK8, and it is not totally ready yet. It is not expected to be feature complete until January 2013 and will not be released before midyear 2013.
However, you can already compile your classes with the JDK 8 preview and make your ideas work.
In this case, your problem can be solved by dividing your application in independent modules. You could do something like:
module foo {
exports foo;
permits bar;
permits baz;
}
Here the module foo can be required only by modules named bar or baz. A dependence from a module of some other name upon foo will not be resolvable at compile time, install time, or run time. If no permits clauses are present then there are no such constraints.
Not sure if alternative frameworks like OSGI, of which you can find implementations in Apache Felix and Eclipse Equinox offer some kind of functionality to implement these levels of encapsulation. It is probable that you may want to investigate a bit about that.
The problem with OSGi without the existence of Jigsaw is that whatever rules enforced by the framework can be broken by reflection, once Jigsaw is ready for public use, though, these rules will be enforced by Java itself, as you read above, at compile time, runtime and install time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With