Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to share package private data between two packages in Java?

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?

like image 434
2 revs Avatar asked Jun 12 '12 02:06

2 revs


1 Answers

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.

like image 199
Edwin Dalorzo Avatar answered Oct 22 '22 09:10

Edwin Dalorzo