Java: new instance from bytecode

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

Answers (3)

Michael Kay
Michael Kay

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

Vladimir Ivanov
Vladimir Ivanov

Reputation: 43108

ClassLoader.defineClass()

Reference:

Upvotes: 8

Amir Afghani
Amir Afghani

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

Related Questions