0

JavaApplication1 wants to instantiate objects defined in the jar file of (fully trusted) JavaApplication2. Not normally a problem - add the external JavaApplication2 jar file to the build path of the JavaApplication1 project and then import the appropriate classes. Simples.

But imagine a scenario where JavaApplication1 needs to use multiple different historical versions of JavaApplication2 at the same time. e.g. Instantiate an instance of a JavaApplication2Object from version 1.5 of JavaApplication2.jar, and then, in the same thread, instantiate a separate instance of JavaApplication2Object from version 1.8 of JavaApplication2.jar.

In C#, I would use reflection to load and interact with the correct DLL. How does one do the same thing in Java in order to deal with the fact that the namespaces and class names are all identical across all versions of JavaApplication2?

Mintaka
  • 21
  • 3

2 Answers2

0

To load different versions of the same class, you have to load them using different class loaders, no way around it.

URL jarV15 = Paths.get("path", "to", "JavaApplication2v15.jar").toUri().toURL();
ClassLoader loaderV15 = new URLClassLoader(new URL[] {url});
Class<?> clazz = loaderV15.loadClass("my.package.JavaApplication2Object");
JavaApplication2Object v15Instance = clazz.getConstructor().newInstance();

Then do the exact same for v1.8.

Alternatively, you can use ServiceLoader instead of manual lookup and instantiation of classes:

ServiceLoader<JavaApplication2Object> serviceLoader = ServiceLoader.load(JavaApplication2Object.class, loaderV15);

Of course, both of your jars need to have proper manifest entries for that.

kaqqao
  • 12,984
  • 10
  • 64
  • 118
0

It really depends on your use case.

If the behavior is trivial, just use a class loader described in kaqqao's answer.

You could also just spawn sub processes with the applicable classpath and for api differences between versions use reflection.

If more complex I would recommend creating helper libraries for each version you care about. You can spawn sub processes with the applicable class path and if data needs to be passed back and forth, set up inter process communication.

bruh
  • 1
  • 1