r/programminghorror • u/Xor_Boole • Jul 04 '15
Yes, Java supports shebangs.
Let Hello.java be the following:
public class Hello {
public static void main(String... args) {
System.out.println("Hello, World!");
}
}Then, running the following shell commands:
javac Hello.java
jar -cfe Hello.jar Hello Hello.class
echo "#\!/usr/bin/env java -jar" > hello
cat Hello.jar >> hello
chmod +x hello
./hellowill produce the output "Hello, World!". Java will ignore the shebang when parsing the jar, until it hits the zip header.
Wat.
0
Upvotes
4
u/notjfd Jul 05 '15 edited Jul 05 '15
There's another way to make java programs start without explicitly calling the runtime, and that's by using a kernel feature called linux_binfmt. As some of you might know, the shebang is actually a so-called magic number. When executing a file, the loader looks at the first few bits of the file, which are usually unique for many file types. If it corresponds with the ELF binary format (linux's "exe"), it will call ld-linux. If it corresponds with the ASCII sequence for the shebang, it will instead parse the next few bytes after it and interpret it as the parser (like python, sh, or other popular script parsers).
The exciting part, however, is that you can add additional definitions to this magic table. This is where linux_binfmt comes in. It exposes a kernel interface which allows you to feed it magic numbers and their corresponding runtime. Two of the most popular uses of these are Java and .NET executables (which have the .exe extension but are not in the win32 binary format and thus have another magic number), which can respectively be opened with the JRE and Mono.