user449265
user449265

Reputation:

Creating an invisible class in a jar

How do I create a jar in java that only one class is visible (public) to users of the jar?

I know I can omit the "public" from the declaration of a class, which makes it visible only to that package, but how do I do it in a jar with several packages, when the visibility should be public to all the classes inside the jar, but not outside of the jar?

Upvotes: 3

Views: 1942

Answers (4)

rsp
rsp

Reputation: 23383

Just a wild idea, but you could play around with a custom classloader that loads files from your .jar which are not recognised as classes otherwise.

For instance you could postprocess class files by encrypting them and storing with your own file extension, then loading and decrypting them from the jar by your custom classloader from the "main" class that is visible to the users of the class. (caveat; I have never tried to do something like this myself :-))

Another method (if the code base isn't too large) might be to develop your classes like normal, run your tests on the package structure and as the last step before packaging use a (perl) script to rebuild your main class by inserting all other classes as private static inner classes and rebuild that. Using this transformation as a pre-package step means you can develop in a sane structure while hiding the implementation classes in the jar.

Upvotes: 0

millimoose
millimoose

Reputation: 39990

You'd have to include all your classes in a single Java package, and omit the "public" modifier in the class definition.

I recommend against this. If you want to indicate a class shouldn't be used by clients of a library, put it in a package named "impl" or "internal" and don't provide public documentation.

Upvotes: 1

Itay Maman
Itay Maman

Reputation: 30733

You're basically looking for the Java counterpart of .Net's assembly-wide visibility. I'm afraid you don't have this ability within the framework of current Java. Future version of Java will offer better support for modules, which should allow something along these lines.

Upvotes: 3

Peterdk
Peterdk

Reputation: 16025

Does using protected as modifier fix this? I know it does allow access for inherited classes, but I don't know about all the other classes in the package.

Upvotes: 0

Related Questions