2011-07-13 70 views
0

我已經使用文件選擇器選擇了一個jar文件,然後使用java反射裝載了jar文件中的所有類。有些類依賴另一個jar文件。Java反射中的類加載異常

但是,當我嘗試獲取類的方法,然後引發下面的異常,因爲這個類有一個導入語句import com.thoughtworks.xstream.XStream;和XStream類在另一個jar文件中定義。

Exception in thread "main" java.lang.NoClassDefFoundError: com/thoughtworks/xstream/io/HierarchicalStreamDriver 
    at java.lang.Class.getDeclaredMethods0(Native Method) 
    at java.lang.Class.privateGetDeclaredMethods(Class.java:2365) 
    at java.lang.Class.privateGetPublicMethods(Class.java:2488) 
    at java.lang.Class.getMethods(Class.java:1406) 
    at com.axway.xtp.testgenerator.templatewizard.MethodSelectionWizardUI.updateListofMethods(MethodSelectionWizardUI.java:744) 
    at com.axway.xtp.testgenerator.templatewizard.MethodSelectionWizardUI$7.widgetSelected(MethodSelectionWizardUI.java:474) 
    at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java:90) 
    at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:66) 
    at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:928) 

我想知道是否有任何方法來防止使用java反射來加載依賴類或jar文件。以下是我用來加載類的一段代碼。

URLClassLoader ucl = new URLClassLoader(new URL[] { new URL("file:" + codeRepository) }); 
JarFile jarFile = new JarFile(new File(codeRepository)); 
Enumeration enm = jarFile.entries(); 
while (enm.hasMoreElements()) { 
    JarEntry entry = ((JarEntry) enm.nextElement()); 

    if (entry.getName().endsWith(".class")) { 
    String fullClassNameWithPath = entry.getName(); 
    String fullyClassifiedClassName = fullClassNameWithPath 
     .replace('/', '.'); 

    try { 
     Class c = ucl.loadClass(fullyClassifiedClassName.substring(
      0, fullyClassifiedClassName.indexOf(".class"))); 
     String className = c.getPackage().getName() + "." 
      + c.getSimpleName(); 
     listClasses.add(className); 
    } catch (Exception e) { 
     continue; 
    } catch (Throwable t) { 
     continue; 
    } 
    } 
} 
+0

不知道這是可能的。你也必須加載依賴庫。 –

回答

1

好吧,如果你的應用程序依賴於類,你最肯定必須包含它的jar(或提供含有包+類的替代路徑)在類路徑上。

0

作爲類加載過程的一部分,您要加載的類所依賴的任何類也將被加載。

我不認爲你有什麼可以做的。