How to create Java classes Dynamically by Java Ref

2020-03-01 01:00发布

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?

4条回答
祖国的老花朵
2楼-- · 2020-03-01 01:17

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.

查看更多
Juvenile、少年°
3楼-- · 2020-03-01 01:22

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

查看更多
家丑人穷心不美
4楼-- · 2020-03-01 01:26

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

查看更多
我命由我不由天
5楼-- · 2020-03-01 01:41

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

查看更多
登录 后发表回答