Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to have the System ClassLoader load .class files specified at run time?

I am writing a static analysis tool for an assignment, it analyses Java bytecode using the ASM library. One of the parts of ASM that we use requires (or at least, appears to require) that the class be loaded from the ClassLoader.

We were hoping the tool would be able to analyse .class files without requiring them on the classpath. We already load the .classes from a specified directory at run time and read them in using an InputStream. This is acceptable for ASM in most cases. There are some classes, such as SimpleVerifier, which attempt to load the classes though.

Is it possible, under this scenario, to register the .class files to be loaded so that calls to Class.forName() will load them? Or is there an easy way to extend the ClassLoader to allow this?


Edit: the information on URLClassLoader was useful. Unfortunately, using Thread.currentThread().setContextClassLoader() to an instance of that didn't work in this scenario. The library code I'm calling into uses a loader it retrieves on instance initialisation using getClass().getClassLoader().

By the time I set the URLClassLoader the class hasn't been initialised so I guess the contextClassLoader does not load that class.

Have I understand the responses correctly? Would using the URLClassLoader to load the 3rd party class be a possibility?

like image 985
Grundlefleck Avatar asked Dec 09 '09 13:12

Grundlefleck


1 Answers

Almost.

If you have classes compiled somewhere, you can load them with a URLClassLoader. You can then set this ClassLoader to be the ClassLoader for the current Thread: Thread.setContextClassLoader(ClassLoader)

Users can that get the current threads context class loader and use that to access the class definition.

like image 92
Kevin Avatar answered Oct 22 '22 03:10

Kevin