Loading an external .class file

suggest change

To load a class from its bytes, a ClassLoader must define it. ClassLoader.defineClass(String, byte[], int, int) is protected, so a subclass can call it. ByteClassLoader extends ClassLoader and adds a public method that forwards to defineClass. The call needs the class name, the class bytes, the offset of the first byte (0, because the data starts at classBytes[0]), and the number of bytes (classBytes.length).

public class ByteClassLoader extends ClassLoader {

    public Class<?> defineClass(String name, byte[] classBytes) {
        return defineClass(name, classBytes, 0, classBytes.length);
    }

}

Now, we have a public defineClass() method. It can be called by passing the name of the class and the class bytes as arguments.

Let’s say we have a class named MyClass in the package stackoverflow.

To call the method we need the class bytes, so we create a Path with Paths.get() and read it with Files.readAllBytes(path). Then we create a ByteClassLoader and call defineClass(). The class name is the binary name: the package, a dot, and the simple class name, in this case stackoverflow.MyClass. The bytes in MyClass.class must use that same name.

Path path = Paths.get("MyClass.class");

ByteClassLoader loader = new ByteClassLoader();
loader.defineClass("stackoverflow.MyClass", Files.readAllBytes(path));

Note: The defineClass() method returns a Class<?> object. You can save it if you want.

To load the class, we just call loadClass() and pass the class name. This method can throw a ClassNotFoundException, so we need a try-catch block.

try{
    loader.loadClass("stackoverflow.MyClass");
} catch(ClassNotFoundException e){
    e.printStackTrace();
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents