2

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.

Nate Schreiner
  • 759
  • 2
  • 7
  • 15
  • To be honest, this is a really nasty and probably dangerous thing to do. But I assume, you just want to use it for "experimentation" and not for any serious production Enviroment. You can take a look a this : [string to code at runtime](https://stackoverflow.com/questions/935175/convert-string-to-code) Thread. But its complicated. – Luxusproblem Mar 16 '20 at 19:28
  • @Luxusproblem Yes this is just for learning purposes. I have updated my question to reflect that. – Nate Schreiner Mar 16 '20 at 20:25
  • 2
    We had [this question](https://stackoverflow.com/q/60664816/2711488) only a few days ago. One of the links I gave in [this comment](https://stackoverflow.com/questions/60664816/create-a-java-class-dynamically-and-compile-and-instantiate-at-run-time#comment107334789_60664816), points to [this answer](https://stackoverflow.com/a/48888184/2711488), which seems to address your issue; using `defineClass` raises errors when your class loader can't deliver dendencies on demand. But it's worth reading the other answers as well. – Holger Mar 17 '20 at 08:23
  • 3
    Well, not sure if "title says it all" but some JVM languages do this, e.g. Clojure by emitting JVM bytecode via ASM library (You can study Clojure compiler code here: https://github.com/clojure/clojure/blob/master/src/jvm/clojure/lang/Compiler.java). I suggest you take this bytecode-generation approach instead of writing out plain java file. – Juraj Martinka Mar 17 '20 at 09:36

0 Answers0