I need to programmatically find out which JRE classes can be referenced in a compilation unit without importing (for static code analysis). We can ignore package-local classes. According to JLS, classes from a package are java.langimported implicitly. The result should be a list of binary class names . The solution should work with simple Java 5 and higher (no Guava, Reflections , etc.) and be an agnostic of the provider.
Any reliable Java-based solution is welcome.
Here are some notes on what I have tried so far:
At first glance, it seems that the question boils down to “How to load all classes from a package?”, Which, of course, is almost impossible, although there are several workarounds (for example, this and also blog posts related to them). But my case is much simpler because the problem with multiple class loaders does not exist. java.langstuff can always be loaded by the / bootstrap class loader, and you cannot create your own classes in this package. The problem is that the system class loader does not divulge its path to the class that related applications rely on.
So far, I have not been able to access the classloader class path of the system, because on the HotSpot virtual machine that I use, it Object.class.getClassLoader()returns nullor Thread.currentThread().getContextClassLoader()can be downloaded java.lang.Objectby delegation, but by itself does not include the class path. Therefore, solutions like this do not work for me. In addition, the list of guaranteed system properties does not include properties with this type of route information (for example, sun.boot.class.path).
It would be nice if I did not assume that there is rt.jar at all, and rather scans the list of resources used by the system class loader. This approach would be safer with respect to implementing a vendor-specific JRE.
source
share