0

I am looking to compile and run Java code - but without writing the .class files to disk. Is it possible to do this with Java?

With Golang, we can use go run <file> and I think it will accomplish the same thing. I am wondering if it's possible to do this with Java source code as well.

Alexander Mills
  • 90,741
  • 139
  • 482
  • 817
  • Sucks that this is a dupe, because the answers to the previous questions are pretty unsatisfactory :( This should be easier to do. – Alexander Mills Mar 25 '17 at 20:59
  • 1
    I have a library to do this. You give it a String and it returns the complied class which you can call. https://github.com/OpenHFT/Java-Runtime-Compiler you can add the class/method as a template to compile just a snippet of code and if that class implements a well know interface you can call it on an instance of the class. – Peter Lawrey Mar 26 '17 at 11:03
  • thanks Peter, man I don't want to mess with a library for this - just looking for a command line switch or something – Alexander Mills Mar 27 '17 at 03:27
  • Java 9 has a REPL and shell for executing code. In Java there are thousands of libraries and you can expect to use quite a few, though keeping them to a minimum is a good idea. – Peter Lawrey Mar 27 '17 at 09:24
  • this is for a library, unfortunately, so solution needs to be generic and probably go back to Java 7 – Alexander Mills Mar 27 '17 at 18:29
  • 1
    ypu can read the source of the library above which works with java 6+ – Peter Lawrey Mar 27 '17 at 18:37
  • @PeterLawrey can you publish your library as a command line tool? – Alexander Mills Apr 11 '17 at 03:14
  • Good idea. I will add an issue for this. – Peter Lawrey Apr 11 '17 at 23:35
  • it will be much more useful as a command line utility, more people will want to use it as a command line util then as a library. Not sure why you'd want to use it as a library. Again think of it like "go run x", but the Java equivalent. I am fairly certain that go run will compile to memory then run the files. – Alexander Mills Apr 11 '17 at 23:37
  • The benefit as a library is you can generate code at runtime which is compiled to byte code. This way you can generate more efficient queries, dynamic data structures which are easier to debug than byte code. – Peter Lawrey Apr 11 '17 at 23:46

0 Answers0