8
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?

starblue
  • 55,348
  • 14
  • 97
  • 151

3 Answers3

8
ClassLoader.defineClass()

Reference:

Sean Patrick Floyd
  • 292,901
  • 67
  • 465
  • 588
Vladimir Ivanov
  • 42,730
  • 18
  • 77
  • 103
2

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);
}
Amir Afghani
  • 37,814
  • 16
  • 84
  • 124
0

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.

Michael Kay
  • 156,231
  • 11
  • 92
  • 164