Question

ClassWriter cw = new ClassWriter(...);
byte[] bytes = cw.toByteArray();

I would like to create new class instance from bytes array. How do I do this? Is it possible at all?

Was it helpful?

Solution

OTHER TIPS

This is possible, and you need to use Reflection in order to achieve this. The psuedo code is:

final Class clazz = loadIntoCurrentClassLoader(bytes); //I'm assuming you wrote this already using defineClass

final YourClass foo ;
try {
    foo = (YourClass) clazz.newInstance();
}
catch (final Exception e) {
    throw new RuntimeException(e);
}

I can create the class by extending ClassLoader and using defineClass. But then the created class has my extended ClassLoader as its ClassLoader, which causes failures when the code of my class loads other classes. Presumably I can get around this by creating my ClassLoader to delegate everything in the right way, but it's not obvious how to get this right.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top