Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hiding classes in a jar file

Is it really impossible to hide some classes in a jar file?

I wanted not to allow direct instantiation of the classes to keep it more flexible. Only the factory (or a facade) should be visible of this jar.

Is there any other way than solve this problem than creating two projects? (Two projects: the first one contains the classes (implementation) and the other one references to the first one and contains the factory; later only the second one will be referenced)

like image 388
nrainer Avatar asked Jan 21 '11 14:01

nrainer


People also ask

What is hiding classes in Java?

Hidden classes are classes that cannot be used directly by the bytecode or other classes. Even though it's mentioned as a class, it should be understood to mean either a hidden class or interface. It can also be defined as a member of the access control nest and can be unloaded independently of other classes.

Why would you package classes in a JAR file?

A JAR file lets you physically organize your classes. You can take any Java files and store them in a JAR file. A JAR file may contain multiple packages, and multiple JAR files may contain files that belong to the same package. So, a JAR file is largely a way to store multiple class files in a single physical file.

Does JAR file contain class files?

The JAR file contains the TicTacToe class file and the audio and images directory, as expected. The output also shows that the JAR file contains a default manifest file, META-INF/MANIFEST. MF, which was automatically placed in the archive by the JAR tool.


2 Answers

If I understand your question correctly, you would like to make sure that users of your library are forced to use your factory to instantiate their objects rather than using the constructors themselves.

As I see it there are two possibilities, one of which is silly but usable in few, specific cases, and the other one is the most practical and probably most commonly used way of doing it.

  1. You could make all your classes into private inner classes of the factory. This would work if you had one factory per class, but is hardly workable if you have a lot of different classes being managed through one factory.
  2. You could use the protected access modifier to restrict access to your class constructors. This is common practice when using the factory pattern.
like image 99
Mia Clarke Avatar answered Nov 01 '22 12:11

Mia Clarke


Obfuscation can help you somehow.

like image 36
jmj Avatar answered Nov 01 '22 13:11

jmj