开发者

Decide on runtime which library needs to be used on JBoss

is there a way to decide during runtime, which class from which jar (deployed on jboss) will be used?

Here is an example:

VERSION1.JAR

package com.something;

public class MyObject {

   public void saySomething() {
       System.out.println("Output from version 1");
   }
}

VERSION2.JAR

package com.something;

public class MyObject {

   public void saySomething() {
       System.out.println("Output from version 2");
   }
}

So in both jars are the same class within the same package but they do different things. Now I want to load MyObject but tell him from which jar I want to use that:

package com.main

public class Main{

   public static void main(String[] args) {

        MyObject v1 = new MyO开发者_高级运维bject();
        v1.saySomething();

        MyObject v2 = new MyObject();
        v2.saySomething();

   }
}

Is that possible? I am using Jboss as application server and I am doing that within a ejb project. So this example is just to explain what I mean. I think maybe with help of the context?


No, you get no control over this. Which one gets loaded is decided by the internals of the JBoss classloader, which is not exposed to your program.

You should avoid situations like this. If you need to control which class gets loaded, you need to put them in different packages.


In java you can dynamically load classes from jar files, but deploying means leaving all decisions to your app-server. In case of jboss, you can define a policy stating which classloaders will have precedence.

If you are trying to implement some kind of plugin system -- then don't deploy the jars. This doesn't mean you can't package your jars with your application. For WARs just don't put them in /WEB-INF/lib. You can put them in eg. /WEB-INF/plugins and use something like this to load them:

ClassLoader parent = Thread.currentThread().getContextClassLoader();
URL url = parent.getResource("/WEB-INF/plugins/plugin-x.jar");
ClassLoader loader = URLClassLoader.newInstance(
    new URL[] { url },
    parent
);
Class<?> clazz = Class.forName("com.something.MyObject", true, loader);
Object myObject = clazz.getConstructor().newInstance();
Method saySomething = class.getMethod("saySomething");
saySomething.invoke(myObject);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜