Skip to content
Advertisement

Creating a New Instance of a class via Reflection with Arguments from multiple Class Loaders

Hello I am trying to create a new instance of a class via reflection:

In the example below the following applies:

  1. This is a method in a subclass of Arg1
  2. Data is an object which stores class references which are associated with each other
JavaScript

This code works when the provided arguments are from the same class loader, yet the code fails when the arguments are from different class loaders. As such, multiple Class Loaders as arguments causes the failure of the method.

Is there any way I can get Java to accept my Arguments from multiple class loaders?

Edit: The reason I have multiple class loaders is due to the fact that I load external jar files which were compiled against this applications API into the application using a custom URLClassLoader.

As to the minimal reproducible example, I cannot at this time provide an example as this is private code which I do not own. The owner of the code would have to give me express permission to upload such an extensive chunk of the code (It’s a bunch of classes that are essentially the cornerstone to the entire application). I can and will run any and all suggestions though and will forward this post to the owner for their approval.

Any help is much appreciated 🙂

Edit 2:

Here the code with debug messages:

JavaScript

Given that Arg1, Arg2 and Foo are Classes which are part of the base application, the output is as follows:

JavaScript

Given that Arg1 and Foo are Classes which are from the same external Jar File and Arg2 remains a class that is part of the base application:

JavaScript

Note: These are the only two use cases

Advertisement

Answer

You cannot use different objects across ClassLoaders. Class Foo loaded from app ClassLoaderFoo loaded from another ClassLoader instance. Please see the following code sample:

JavaScript

Depending on you usage, this might not be the most efficient solution, but one that will always work. A better solution would be using reflection, but you will be forced to do everything with reflection. Something like this:

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement