java urlclassloader,它调用具有导入依赖关系的类

时间:2014-01-13 05:35:47

标签: java classpath urlclassloader

在urlclassloaders上的其他帖子中提供一些帮助后 - understanding urlclassloader, how to access a loaded jar's classes  我有一个跟进问题,因为我认为我没有正确地解决问题。

myPackageA.start有一个urlclassloader,呼叫myPackageB.comms
myPackageB.comms依赖于import org.jgroups.JChannel 使用以下代码形成/home/myJars/jgroups-3.4.2.Final.jar

    package myPackageB;

    import org.jgroups.JChannel;

    public class SimpleChat {
     JChannel channel;
     String user_name=System.getProperty("user.name", "n/a");

        private void start() throws Exception {
            channel=new JChannel();
            channel.connect("ChatCluster");
            channel.getState(null, 10000);
            channel.close();
        }

        public static void main(String[] args) throws Exception {
            new SimpleChat().start();
        }
    }

通常我会用java -cp /home/myJars/jgroups-3.4.2.Final.jar:myPackageB myPackageB.SimpleChat调用上面的代码并按预期运行。

我的问题是如何在脚本中设置-cp,以便在使用以下代码从myPackageB.SimpleChat

调用java -cp myPackageA.jar myPackageA.start时导入有效
package myPackageA;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;

public class start 
{
    Class<?> clazz;

    private void start() throws Exception 
    {
        if (this.clazz == null)
            throw new Exception("The class was not loaded properly");

       Object mySc = this.clazz.newInstance(); 
        Method sC = this.clazz.getDeclaredMethod("main", String[].class);
        String[] params = null; 
        sC.invoke(mySc,  (Object) params);
    }

    public void loadSc() throws Exception
    {
        URL classUrl;
        classUrl = new URL("file:///home/myJars/myPackageB.jar");
        URL[] classUrls = { classUrl };
        URLClassLoader ucl = new URLClassLoader(classUrls);
        Class<?> c = ucl.loadClass("myPackageB.SimpleChat");
        this.clazz = c;
     }

     public static void main(String[] args) throws Exception 
     {
         start startnow = new start();
         startnow.loadSc();
         startnow.start();
     }
}

感谢
领域

1 个答案:

答案 0 :(得分:0)

只需将jgroups-3.4.2.Final.jar的网址添加到URLClassLoader's网址数组中。