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?

3
  • 1
    possible duplicate of Java: How to load Class stored as byte[] into the JVM? Commented Nov 23, 2010 at 17:44
  • @bruno conde: It looks like. We just express things in a more concise way here Commented Nov 23, 2010 at 17:54
  • You can use defineClass, however unless you use a custom class loader you may need to use reflections to call it as its not a public method. Commented Nov 23, 2010 at 22:39

3 Answers 3

8
ClassLoader.defineClass()

Reference:

Sign up to request clarification or add additional context in comments.

3 Comments

Nice answer but awful formatting and a java 1.4 link. Changed both.
thanks for editing, was struggling with that, but parser didn't want to show the link properly.
+1. Anyway, the method is protected, so you'll need a way to access it. Extending the ClassLoader and providing a public method could be a solution.
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);
}

4 Comments

I'm pretty sure the loadIntoCurrentClassLoader(bytes) part is what the question is about :-)
Ok so I went a little overboard ;)
It's ambiguous from the way the question is phrased.
The point is not clazz.newInstance(). The point here was how to get clazz. Reflection does not help here, you should use classLoader.defineClass()
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.