Java: new instance from bytecode?

ClassLoader.defineClass() Reference: ClassLoader. DefineClass(String name, byte b, int off, int len).

1 Nice answer but awful formatting and a java 1.4 link. Changed both. – Sean Patrick Floyd Nov 23 '10 at 17:49 thanks for editing, was struggling with that, but parser didn't want to show the link properly.

– Vladimir Ivanov Nov 23 '10 at 17:50 3 +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.

– Tomas Narros Nov 23 '10 at 17:51.

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); }.

I'm pretty sure the loadIntoCurrentClassLoader(bytes) part is what the question is about :-) – Sean Patrick Floyd Nov 23 '10 at 17:49 Ok so I went a little overboard ;) – Amir Afghani Nov 23 '10 at 17:50 It's ambiguous from the way the question is phrased. – Amir Afghani Nov 23 '10 at 17:50 The point is not clazz.newInstance(). The point here was how to get clazz.

Reflection does not help here, you should use classLoader.defineClass() – AlexR Nov 23 '10 at 19:03.

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.

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions