2

Hey I wanted to know if it is possible to compile java source code that is saved in a string and get and output stream of the bytecode without writing it into a file.

If yes, I'd love to know how and it would save me a lot of time as I couldnt find anything helpful so far.

Thanks alot!

tud_mb
  • 65
  • 6
  • Related question: https://stackoverflow.com/q/11925497/2513200 – Hulk Aug 24 '20 at 21:34
  • 2
    Does this answer your question? [How do I programmatically compile and instantiate a Java class?](https://stackoverflow.com/questions/2946338/how-do-i-programmatically-compile-and-instantiate-a-java-class) – Hulk Aug 24 '20 at 21:36
  • Not really :/ Just to give you guys more context: Im working on platform which generates a jar file from the users input source code and the source codes that are saved in the database. We cant just create .class files locally and then add them to a jar and delete them. I want to add JarEntrys directly to the JarOutputStream and then append the bytecode of the compiled source code. Therefore I have to save the compiled bytecode in memory instead of generating a seperate file. – tud_mb Aug 24 '20 at 21:54
  • Well, in that case please elaborate a bit in your question - it's hard to guess what you already know about dynamic compilation, and what exactly you need. – Hulk Aug 24 '20 at 22:03
  • I'm really new to dynamic compilation. I've been trying alot here and there with static compilation which worked fine, but just wasnt what I looked for :/ – tud_mb Aug 24 '20 at 22:05
  • I'm not sure if this helps in your use-case, but there is a way to take the stored source code and execute it dynamically with a library like jOOR - https://github.com/jOOQ/jOOR Sample code from the link above: Supplier supplier = Reflect.compile( "com.example.HelloWorld", "package com.example;\n" + "class HelloWorld implements java.util.function.Supplier {\n" + " public String get() {\n" + " return \"Hello World!\";\n" + " }\n" + "}\n").create().get(); // Prints "Hello World!" System.out.println(supplier.get()); – Loathian Aug 24 '20 at 23:59
  • 2
    The pointer given in [this comment](https://stackoverflow.com/questions/63568852/compile-java-source-code-from-string-and-save-output-to-stream-instead-of-a-file#comment112410328_63568852) is going into the right direction. You have to implement a `JavaFileManager`. See, e.g. [this answer](https://stackoverflow.com/a/41003305/2711488). It handles the input side, showing how a runtime string as source code input as well as a byte array for an already compiled dependency is possible. It should be straight-forward to adapt it, to also customize the output side. – Holger Aug 25 '20 at 08:01
  • Thank you guys for your help. It helped me alot to understand what I have to do and http://openbook.rheinwerk-verlag.de/java7/1507_19_002.html#dodtpfa3ba747-36ff-403e-8232-81968f6509c0 this link helped me to achieve what I wanted to do (even tho its german) – tud_mb Aug 26 '20 at 13:46

0 Answers0