简体   繁体   中英

Using ClassLoader.defineClassCond to get a Class object from bytes of a class created through ASM, NoClassDefFoundException?

I've generated a class by taking the bytes of a base class and accepting them through a custom class adapter. When I call define class on the bytes produced as a product of the base class I get this error:

Caused by: java.lang.NoClassDefFoundError: com/example/MyClassBase
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClassCond(Unknown Source)
    ... 24 more
Caused by: java.lang.ClassNotFoundException: com.example.MyClassBase
        at java.net.URLClassLoader$1.run(Unknown Source)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        ... 26 more

The base class has been loaded by a URLClassLoader from a jar. Is there some underlying method call in defineClass that is throwing the exception because it cannot locate the loaded class? How can I fix this?

Keep in mind that it won't be practical to load the base class a different way. As a parameter to the problem I would say assume that it must be loaded through a URLClassLoader from another jar.

I think you're trying to load modified bytecode that relies on com.example.MyClassBase via a ClassLoader that can't see that class. When you create your own ClassLoader instance to load your modified class, you should be chaining it to an existing ClassLoader using its constructor to establish a parent/child hierarchy of loaders, which helps avoid this exact problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM