在JVM中动态生成类的运行时操作

huangapple 未分类评论51阅读模式
标题翻译

Dynamic class generation at runtime in the JVM

问题

我需要在运行时获取输入,并基于输入创建一个新的类,然后将其加载到JVM中运行。

尽管这可能很快变成一个抽象问题,具体答案很少,因此可能会被标记为“不适合在stackoverflow上提问”,但我确实正在寻找一些关于此的具体答案。

我已经阅读了大量关于此的资源。我找到的答案范围从操作字节码(甚至不知道如何开始)到递归加载JVM中的所有类,但实际上这似乎不可能,因为这似乎会导致无限循环的情况。

目前,我正在动态地编写一个 .java 文件,然后获取对系统编译器的引用,并使用它编译为一个类文件。然后我使用 ClassLoader 类上的 defineClass() 方法来尝试将其加载到JVM中。

在执行这些步骤之后,我会抛出 NoClassDefError,这是有道理的,我只需要一些关于如何将这个新的、动态编写的类正确加载到JVM中的输入?

针对某人评论中提出的一个关注,这完全是为了实验和学习目的,不会投入生产使用。

英文翻译

I need to take input at runtime and create a new class with it, and load it into the JVM to run.

Although this can quickly become an abstract question with minimal concrete answers, and therefore be marked "Not appropriate for stackoverflow", I really am looking for some concrete answers on this.

I have read a ton of resources regarding this. Answers I've uncovered range from manipulating the byte code (not even sure how I would begin that), to recursively loading all classes in the JVM which doesn't actually seem possible because this seems like it would cause an infinite loop type scenario.

Currently I'm writing a .java file dynamically and then getting a refference to the System compiler and using that to compile to a class file. Then I use the defineClass() method on the ClassLoader class to attempt to load it into the JVM.

After performing these steps I'm getting a NoClassDefError thrown which makes sense, I just need some input on how to correctly get this new, dynamically written class loaded into the JVM?

In response to a concern brought forth by someones comment, this is 100% experimentation and for learning purposes only. This is not something that would go into production.

huangapple
  • 本文由 发表于 2020年3月17日 03:13:04
  • 转载请务必保留本文链接:https://java.coder-hub.com/60711934.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定