shijie xu shijie xu - 1 year ago 59
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;
expClass =defineClass(className, b, 0, b.length);
return expClass;

return null;

When I try to run the code (the
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(
at java.lang.ClassLoader.defineClass(
at java.lang.invoke.ByteCodeClassLoader.load(


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
is protected package.

Answer Source

Javadoc of defineClass() says:

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download