How do I obtain classpaths from a VirtualMachine?

75 views Asked by At

I have a VirtualMachine from which I want to extract "classpaths". The VM in this case is launched using a RawCommandLineLauncher.

The closest thing I could find is the VirtualMachine method allClasses, but I would like one step above that and get a list of class directories instead. Is this possible?

I tried:

  • Obtaining a ClassLoader from the VM. Don't think this is possible.
  • Using the JDI implementation for this. Unfortunately the method is not public.
2

There are 2 answers

0
Michael On BEST ANSWER

You can check and cast to a subinterface, PathSearchingVirtualMachine

if (vm instanceof PathSearchingVirtualMachine psvm) {
    List<String> cp = psvm.classPath();
}

Above example uses instanceof pattern matching, which is a newer language feature. If you're on an older version of Java then do a normal cast.

1
SpaceTrucker On

The jinfo <pid> command offers some insight. For example it contains the following for a running eclipse instance for me:

[...]
VM Arguments:
[...]
java_class_path (initial): C:\foo\bar\eclipse\jee-2022-06\eclipse\\plugins/org.eclipse.equinox.launcher_1.6.400.v20210924-0641.jar
[...]

However this is only the initial class path when the application was started. Depending on the application it may create additional classloaders on runtime information and hence extend the classpath during runtime. For example if you are running a spring boot fat jar, the initial classpath will contain the fat jar and hence all of the additional classes besides the jvm classes itself. However this fat jar is in the spring boot format and the actual classpath consists of the jars contained in the fat jar.