0

I'm trying to make a simple application that loads and runs some classes during runtime. For example, let's say I have this config:

module1.classpath=module1.jar,somelibs1.jar
module1.class=com.blabla.Module1
module2.classpath=module2.jar,somelibs2.jar
module2.class=com.blabla.Module2

Then I need to load libraries specified in module1.classpath and run the module1.class with that libraries loaded. Afterwards I need to load module2.classpath and run module2.class with those libraries.

How do I handle the case when somelibs1.jar and somelibs2.jar have the same classes inside? Basically I'd like to run module1.jar using exclusively somelibs1.jar and module2.jar using exclusively somelibs2.jar. How do I implement that?

I'm guessing I need to create a separate classloader for each of my classes and push the jars in that classloaders. However I'd appreciate some example or at least a confirmation that it is a right way to do that.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
bezmax
  • 25,562
  • 10
  • 53
  • 84

2 Answers2

1

This seems to be a pretty good use case for OSGI. I would recommend using OSGI for this as everything you nees is provided by OSGI out-of-box.

But if for some reason you can't use OSGI, then what you need to do is to have a classloader for each module. Load the moduleX.class by a ClassLoaderX, and moduleX.classpath should be added in to ClassLoaderX's path. You can use a set of simple URLClassLoader for this.

Suraj Chandran
  • 24,433
  • 12
  • 63
  • 94
  • Thanks, I think this fully covers the question. Also special thanks for mentioning about OSGI, now I know that it exists and reading about it :D – bezmax Jun 16 '11 at 07:52
0

Thanks for question. Very interesting.

It seems to you can't use several versions of the same class in one instance of JVM. I've never had this task and I don't know how to implement this.

But let's play. I don't know what is exotic application do you develop. May be you can run many JVMs and each JVM will have exclusive CLASSPATH.

Write application which can run (for example using Runtime.exec()) another JVM and make a conversation to it via some channel (may be network).

Nikolay Antipov
  • 920
  • 2
  • 8
  • 17
  • Loading it in separate JVM would be too resource consuming. The approach proposed by Suraj Chandran is much better as it allows to load everything in one JVM using separate classloaders. – bezmax Jun 16 '11 at 07:54
  • hmmm. May be. But you can examine how OSGi works. This is a very heavy solution. Well, your decision is your decision:-). Good luck! – Nikolay Antipov Jun 16 '11 at 08:07