Reputation: 9112
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?
Upvotes: 8
Views: 1286
Reputation: 163539
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.
Upvotes: 0
Reputation: 38541
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);
}
Upvotes: 2