Is there a guarantee that (the default, system) Java class loader doesn't attempt to load classes that aren't referred to in the code being run? A couple of examples of what I mean:
framework.jar
which I know to contain references to another library.jar
's classes in it, but I'm using only such part of the framework that doesn't contain those references. Is it safe to leave library.jar
out?Quickly testing it seems to work as assumed above, and it wouldn't make much sense to load unused classes anyway, but is there any guarantee on this?
Addition: It seems that my "static blocks are run when a class is first loaded" statement above is somewhat incorrect. It's definitely possible to load classes (one thing) without running them (another thing). So I'm interested in both cases; guarantees about classes not getting loaded, and not getting run.
There is no such guarantee1 wrt the loading of the classes.
However, you are guaranteed that static blocks won't be run prematurely. The events that trigger class initialization are specified in JLS 12.4.1.
A class or interface type T will be initialized immediately before the first occurrence of any one of the following:
- T is a class and an instance of T is created.
- T is a class and a static method declared by T is invoked.
- A static field declared by T is assigned.
- A static field declared by T is used and the field is not a constant variable (§4.12.4).
- T is a top-level class, and an assert statement (§14.10) lexically nested within T is executed.
1 - It is observed that current generation Java implementations do not load classes unnecessarily, but that is not a guarantee. The only guarantees are what it written in the official specifications.