user1589188
user1589188

Reputation: 5736

Get reference to Class from another class loader at runtime in JAVA

I am running some domain specific scripts in a new thread of an application. The classloader in the thread only has all the classes of the application.

The application also has a module that loads additional classes in jars in a folder at runtime (classes created outside of the application), providing additional functionalities to other parts of the application.

Unfortunately, these two classloaders are not merged and when running my scripts I cannot load any class that I know is there in one of the external jars.

Tried this.getClass().getClassLoader().loadClass("external.cls") no go.

I also tried Reflections reflections = new Reflections("external.cls") without success.

Is there a way to gain access to those classes in my script running thread at runtime? Something like:

Upvotes: 1

Views: 3109

Answers (2)

Pavel S.
Pavel S.

Reputation: 1224

Create a static reference to the additional class loader in one of your main application's classes. When loading additional classes for the first time, set it up. When running scripts, it will already be there to provide you with additional classes, already loaded and cached by the JVM, or to load more of them not yet loaded. Such a dependency of the main class loader on the additional one will correctly reflect the fact that the application depends on the additional module.

Upvotes: 0

GhostCat
GhostCat

Reputation: 140457

Most of the options you outlined in your question would work.

Use reflection to get the external class from the two class loaders?

Would not. Class loading is about finding classes in the classpath, and making them available. Reflection doesn't help there. It doesn't matter if you load a class because it is directly referenced in a class file; or because you call Class.forName().

For the other two options:

Load the external jars again in my script running thread?

is probably the "easiest" to implement; but of course, it means re-loading classes; in other words: doing work again. Depending on the amount of classes we are talking about, this could be insignificant, or pretty costly.

Gain access to another class loader that loaded the external class?

would require you to rework that "script class" loader. When it doesn't find a class, it has to delegate the loadClass() call to those "other" class loaders.

Most likely, your first option could be implemented in a clean, straight forward way - but it doesn't come for free; you have to write the code to make that happen.

Upvotes: 2

Related Questions