-1

I was wondering if it is possible to pass code as an argument to the Java CLI and have it compile and run the code in memory instead of having to write it to a file, compile the file, run the compiled file, then delete everything. If not, is there a way to emulate this behavior in a UNIX environment (Linux/macOS)?

Example:

> java --code 'public class Main { public static void main(String[] args) { System.out.println("Hello, world."); } }'

nrubin29
  • 1,522
  • 5
  • 25
  • 53
  • You may have more success with one of the JVM-based scripting languages (like Groovy or Beanscript) – Thilo Jan 16 '17 at 04:33
  • You could write some Java code that would allow you to get close to this behavior. You can have Java code stored only in memory, but Java requires you to have the class files actually be written to disk. So you would still have to delete those after you have finished with them. – Michael Sharp Jan 16 '17 at 04:37
  • Also note that almost any Java program you are going to write will want to use a couple of third-party libraries. The JVM-scripting tools usually have support for fetching dependency jars from the Maven repositories. – Thilo Jan 16 '17 at 05:00
  • Have a look at http://stackoverflow.com/questions/935175/convert-string-to-code/30038318#30038318 – Marco13 Jan 16 '17 at 05:21

1 Answers1

0

You can do it usin bash.

Basicaly it will look like this:

#!/bin/bash

while getopts ":c" opt; do
  case $opt in
    c)
      echo $2 > ./Main.java
      javac Main.java
      ;;
    \?)
      echo "Invalid option: -$OPTARG" >&2
      ;;
  esac
done

It takes the argument c as code, saves it to temporary file and compiles. You can delete if it is unnecessary by adding rm Main.java later.

Adil Aliyev
  • 1,159
  • 2
  • 9
  • 22