Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
我正在用 Java 编写一个带有 REPL 的玩具解释器。我想从语言生成字节码并运行它,而不是解释 AST 并运行它。
由于我的 Java 有点生疏,是否可以在 JVM 上动态运行生成的字节码?
您可以使用 java.lang.Classloader.defineClass(),它将字节码转换为 Class 对象。您可以在生成的 Class 对象上调用 newInstance(),然后就可以了。
查看 Javassist,它包含一个片段编译器,允许您将 Java 片段编译为字节码,并将它们定义为类中的方法,然后您可以调用该方法。