2014-01-13 90 views
0

在urlclassloaders上的其他線程中獲得一些幫助之後 - understanding urlclassloader, how to access a loaded jar's classes 我有一個關於問題的問題,因爲我認爲我沒有正確處理該問題。java urlclassloader調用具有導入依賴關係的類

myPackageA.start具有的URLClassLoader主叫myPackageB.comms
myPackageB.comms具有用下面的代碼

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上面的代碼的相關性,以import org.jgroups.JChannel 形式/home/myJars/jgroups-3.4.2.Final.jar和運行正常。

我的問題是howit可以設定在腳本中的-cp因此使用下面的代碼時,進口的作品叫myPackageB.SimpleChatjava -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(); 
    } 
} 

感謝
藝術

回答

0

只需添加URL對於jgroups-3.4.2.Final.jarURLClassLoader's的URL數組。

+0

你能舉個例子,thx藝術 –