shijie xu shijie xu - 4 months ago 11
Java Question

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.

Answer

Javadoc of defineClass() says:

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

Comments