2012-09-12 2 views
1

classLoader를 사용하여 jar 파일에서 클래스를로드하려고했습니다. 여기 내 코드는 다음과 같습니다.jar 파일에서 클래스를로드 할 때 java.lang.ClassNotFoundException이 발생했습니다.

private void loadJar(String path, String className) { 

    try { 

     File file = new File(path); 

     if (!(file.exists())) { 
      log.error("JAR File not found!"); 
      return; 
     } 

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

     System.out.println("className: "+className); 
     Class aClass = classLoader.loadClass(className); 

     if (!(isNullaryConstructor(aClass))) { 
      System.out.println("Non nullary Constructor detected!"); 
      return; 
     } 

     Object anInstantiation = aClass.newInstance(); 

    } catch (MalformedURLException e) { 
     e.printStackTrace(); 
    } catch (InstantiationException e) { 
     e.printStackTrace(); 
    } catch (IllegalAccessException e) { 
     e.printStackTrace(); 
    } catch (ClassNotFoundException e) { 
     e.printStackTrace(); 
    } catch (SecurityException e) { 
     e.printStackTrace(); 
    } catch (IllegalArgumentException e) { 
     e.printStackTrace(); 
    } 
} 

주 클래스의 테스트 작업 영역에서 시도해 보았습니다. 그리고 그것은 작동합니다.

하지만 프로젝트에 통합했을 때. 이 오류가 발생했습니다 :

java.lang.ClassNotFoundException 

저는 Maven을 사용하고 있습니다. 의존성에 뭔가를 추가해야합니까?

public static void main(String[] args) throws Exception { 

    JarFile jf = new JarFile(new File(jarPath)); 

    Enumeration<JarEntry> e = jf.entries(); 
    while (e.hasMoreElements()) { 
        JarEntry entry = e.nextElement(); 
     System.out.println(entry.toString()); 
    } 
    jf.close(); 
} 

을 내가 입력 한 이름은 정확했다 :

나는 클래스 이름이 코드와 맞는지 확인하기 위해 내 jar 파일에 존재하는 클래스를 나열.

도와주세요.

감사합니다 :)

답변

0
  1. URL은 아마도 잘못된 것입니다. 대신 file.toURI().toURL()을 시도하십시오. 또는 !/을 삭제하십시오. 표준 Java 클래스 로더는이 구문을 지원하지 않습니다.

  2. 클래스 이름이 잘못되었을 수 있습니다. ..class 확장자로 분리 된 요소를 사용하여 패키지 이름과 함께 정규화 된 이름을 사용해야합니다. String의 경우 java.lang.String

관련 문제