2013-12-12 4 views
4

항아리에서 클래스를로드하려고하는데 classLoader를 사용하고 있습니다.항아리에서 클래스로드

클래스 로더 준비를 위해 나는이 코드 부분이 :

private void loadClass(){ 

    try{ 
     JarFile jarFile = new JarFile(Path); 
     Enumeration e = jarFile.entries(); 

     URL[] urls = { new URL("jar:file:" + Path +"!/") }; 
     classLoader = URLClassLoader.newInstance(urls); 


    } catch (MalformedURLException ex) { 
     // TODO Auto-generated catch block 
     ex.printStackTrace(); 
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 

} 

가 지금은 클래스를로드를, 나는

....   
      loadClass(); 

      Class device = classLoader.loadClass("org.myPackage.MyClass"); 

      MyMotherClass Device = (MyMotherClass) device.newInstance(); 
... 

MyClass에이 MyMotherClass의 확장하는 새 인스턴스를 얻기 위해 시도 때 나는 classLoader.loadClass ("org.myPackage.MyClass"), classLoader에있는 MyMotherClass를 수행한다. 지금이 순간에.

이제 device.newInstance()에서 예외가 발생합니다. 문제는 MyClass에서 사용하는 다른 클래스가 클래스 경로에 없다는 것입니다.

어떻게해야합니까?

필요한 모든 클래스를 classLoader에로드하는 다른 방법이 있지만 새 인스턴스를 가져올 때 작동하지 않습니다. MyClass 및 다른 항목을 변경할 수 없습니다.

+0

JVM을 시작하기 전에 클래스 경로 설정을 변경할 수 있습니까? – Bathsheba

+1

이것이 도움이됩니까? @stackoverflow.com/questions/402330/is-it-possible-to-add-to-classpath-dynamically-in-java –

+0

@Bathsheba 아니요, 항아리가로드되어야하는지 모르겠습니다. . 런타임시 생성되는 이름 – Clonw

답변

2

런타임시 동적으로 jar를로드하는 데 사용하는 코드가 있습니다. 나는 당신이 이 실제로는이 일을하지 않는다는 사실을 회피하기 위해 리플렉션을 이용합니다. 즉, JVM이 시작된 후에 클래스 경로를 수정하십시오.. 단지 my.proprietary.exception을 현명한 것으로 변경하십시오.

/* 
    * Adds the supplied library to java.class.path. 
    * This is benign if the library is already loaded. 
    */ 
    public static synchronized void loadLibrary(java.io.File jar) throws my.proprietary.exception 
    { 
     try { 
      /*We are using reflection here to circumvent encapsulation; addURL is not public*/ 
      java.net.URLClassLoader loader = (java.net.URLClassLoader)ClassLoader.getSystemClassLoader(); 
      java.net.URL url = jar.toURI().toURL(); 
      /*Disallow if already loaded*/ 
      for (java.net.URL it : java.util.Arrays.asList(loader.getURLs())){ 
       if (it.equals(url)){ 
        return; 
       } 
      } 
      java.lang.reflect.Method method = java.net.URLClassLoader.class.getDeclaredMethod("addURL", new Class[]{java.net.URL.class}); 
      method.setAccessible(true); /*promote the method to public access*/ 
      method.invoke(loader, new Object[]{url}); 
     } catch (final NoSuchMethodException | 
      java.lang.IllegalAccessException | 
      java.net.MalformedURLException | 
      java.lang.reflect.InvocationTargetException e){ 
      throw new my.proprietary.exception(e.getMessage()); 
     } 
    } 
+0

이 코드는 잘 작동합니다! 고맙습니다!!! – Clonw