I'm writing a toy interpreter with a REPL in Java. I'd like to generate bytecode from the language and run that, instead of interpreting an AST and running that instead.
我正在用Java编写一个带有REPL的玩具解释器。我想从语言生成字节码并运行它,而不是解释AST并运行它。
Since my Java is a bit rusty, is it possible to run generated bytecode on the fly on the JVM?
由于我的Java有点生疏,是否可以在JVM上动态运行生成的字节码?
2 个解决方案
#1
You can use java.lang.Classloader.defineClass(), which turns bytecode into a Class object. You can the call newInstance() on the resulting Class object, and off you go.
您可以使用java.lang.Classloader.defineClass(),它将字节码转换为Class对象。你可以在生成的Class对象上调用newInstance(),然后离开。
#2
Have a look at Javassist which contains a snippet compiler allowing you to compile Java snippets to bytecode and define them as a method in a class which you can then invoke.
看看Javassist,它包含一个片段编译器,允许您将Java片段编译为字节码,并将它们定义为类中的一个方法,然后您可以调用它。
#1
You can use java.lang.Classloader.defineClass(), which turns bytecode into a Class object. You can the call newInstance() on the resulting Class object, and off you go.
您可以使用java.lang.Classloader.defineClass(),它将字节码转换为Class对象。你可以在生成的Class对象上调用newInstance(),然后离开。
#2
Have a look at Javassist which contains a snippet compiler allowing you to compile Java snippets to bytecode and define them as a method in a class which you can then invoke.
看看Javassist,它包含一个片段编译器,允许您将Java片段编译为字节码,并将它们定义为类中的一个方法,然后您可以调用它。