Search code examples
javawindowsshebang

How do I run a java class with a shebang line on Windows?


I have some java utilities written to be used with the shebang line supported by Java 11. They work fine on my Mac, but I now need to use them on Windows, and Windows doesn't support the shebang line, Is there a way to do this?


Solution

  • While Windows doesn't support the shebang line, the Java runtime will still run a java source file that conforms to the limitations for shebang-line java classes. (This basically means it must be contained in a single source file and not call any outside libraries. Standard Java libraries still work.)

    Here's how I did it for a class I wrote called UuidGen.java:

    First, I commented out the Shebang line, since it doesn't get used.

    Second, I created a batch file called uuid.bat:

    @echo off
    java %~db0\UuidGen.java %*
    

    Third, I put this file in the same directory as the UuidGen.java file.

    Fourth, I put this directory on the system path.

    Now, to run it, all I need to do is type uuid.

    The %~db0 in the path gets replaced by the path to the .bat file being executed. The %* at the end passes all the parameters of the .bat command to the java command.

    (If anyone can come up with a cleaner way to do this, I'd love to see it.)