开发者

Class loading Exception in java reflection

开发者 https://www.devze.com 2023-03-20 05:15 出处:网络
I have selected a jar file using file selector, then loaded all the classes in the jar file using java reflection. Some classes has dependency on another jar file.

I have selected a jar file using file selector, then loaded all the classes in the jar file using java reflection. Some classes has dependency on another jar file.

But when I try to get method of class then following exception is thrown because this class has a import statement import com.thoughtworks.xstream.XStream; and XStream class is defined in another jar file.

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)

I wanted to know that is there any way to prevent the dependency class or jar file to be loaded using java reflection. Following are the piece of code I am using to load classes.

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 cl开发者_开发百科assName = c.getPackage().getName() + "."
          + c.getSimpleName();
      listClasses.add(className);
    } catch (Exception e) {
      continue;
    } catch (Throwable t) {
      continue;
    }
  }
}


Well, if your application depends on that class, you most definitely need to have the jar containing it (or provide an alternative path containing the package+class) on the classpath.


As part of the classloading process, any classes which the class you want to load depends upon will also be loaded.

I don't think there's anything you can do about that.

0

精彩评论

暂无评论...
验证码 换一张
取 消