Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 579
Denis Kniazhev Avatar asked Nov 23 '10 17:11

Denis Kniazhev


2 Answers

ClassLoader.defineClass()

Reference:

  • ClassLoader.defineClass(String name, byte[] b, int off, int len)
like image 98
Vladimir Ivanov Avatar answered Nov 20 '22 11:11

Vladimir Ivanov


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);
}
like image 37
Amir Afghani Avatar answered Nov 20 '22 09:11

Amir Afghani