0

Reflection is used to load java class classes and manipulate them on the fly. But I have across a weird question that is asking me how to create Java classes on the fly by Reflection.I mean the classes is not compiled or have source code till we want them created. Is it really possible? Any examples?

asked Feb 3, 2012 at 8:15

4 Answers 4

2

You can take a look look at Bean Shell's eval method It lets you execute any Java code on the fly without the need to compile the code into bytecode. You can pass a string containing all the Java code for your class to it's eval method and you'll get back an instance of the dynamically created class. Let me know if you're interested in it and want me to give you an example.

answered Feb 3, 2012 at 8:23
1
  • 1
    but the the class denoted by className is not compiled, there is no trace of it in the byte code nor source code. forName() will fail, won't it? Commented Feb 3, 2012 at 8:24
1

Seems to me you don't need reflection, but just need to call the JavaCompiler directly from your code: JavaCompiler.

answered Feb 3, 2012 at 8:23
0

You can try ASM ASM

or Byte code engineering library

Byte code engineering library

for manipulating, creating classes at run time

In .NET we have Reflection.Emit(C#) which can do that Reflection.Emit

Not sure whether there is a direct java equivalent. You can see another similar question on SO here Java equivalent of reflection.emit

answered Feb 3, 2012 at 8:26
1
  • byte code manipulation is neede. Actually Javassist library is just what I needed. Commented Feb 4, 2012 at 11:13
0

Maybe Apache DynaBeans will do. You can find some tutorials on creating and manipulating them eg. here: http://www.javaranch.com/journal/2003/07/TouringTheCommonsPart1.html

answered Feb 3, 2012 at 8:22

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.