简体   繁体   中英

Load byte array as a class in Java system packages

Anyone has idea how to class load a dynamically generated bytecode, which is expected to be in Java system class package (the package name starts with java.lang....).

public class ByteCodeClassLoader extends ClassLoader{
    public static Class<?> run(String className, byte[] b){
         ....
         return load(className, b);
    }
    public   Class<?> load(String className,  byte[] b){
            .............
            Class<?> expClass = null;
            synchronized(this){
                expClass =defineClass(className, b, 0, b.length);
            }
            return expClass;

        return null;
    }

When I try to run the code (the className is java/lang/invoke/DYNGuardWithTestHandle0), it throws exception:

java.lang.NoClassDefFoundError: java/lang/invoke/DYNGuardWithTestHandle0
    at java.lang.ClassLoader.defineClassImpl(Native Method)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:346)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:283)
    at java.lang.invoke.ByteCodeClassLoader.load(ByteCodeClassLoader.java:83)
    at java.lang.invoke.ByteCodeClassLoader.run(ByteCodeClassLoader.java:54)

Thanks.


The given name is java/lang/invoke/DYNGuardWithTestHandle0, while the class name in the byte[] stream is java.lang.invoke.DYNGuardWithTestHandle0. After making both consistent, the class loading would still fail because the package java.lang is protected package.

Javadoc of defineClass() says:

Throws NoClassDefFoundError if name is not equal to the binary name of the class specified by [byte array]

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