javacmdjavac

How to Auto Compile For the Command Line Using Javac From Within a Class?


Is there code for a class to automatically call javac when it is executed via the command line? Such as calling java Text, and within Text.java a section of code is run that automatically calls javac Text.java to re-compile the byte code.

I want to make it easier to edit a file through eclipse, and then run it via the command line without having to manually type javac over and over to rec-compile the classes byte code to reflect new changes.


Solution

  • Compile and run with java

    Java 11 and later can "execute" a Java source file directly so it does not have to be compiled with javac first (by transparently invoking the compiler in the process)

    From JEP 330 (https://openjdk.java.net/jeps/330)

    For example, if a file called Factorial.java contains a class called Factorial to calculate the factorials of its arguments, then the command

    java Factorial.java 3 4 5 
    

    is informally equivalent to

    javac -d <memory> Factorial.java 
    java -cp <memory> Factorial 3 4 5
    

    If you use this, please report back how it worked for you.