Up to and including Java
6 it was possible
to do this using the Static Initialization Block
For instance using the following code:
public class Foo {
static {
System.out.println("Message");
System.exit(0);
}
}
The
System.exit(0)
lets the program exit before the JVM is looking for the main
method,
otherwise the following error will be thrown:
Exception in thread "main" java.lang.NoSuchMethodError: main
Sequence is as follows:
·
jvm loads class
·
executes static blocks
·
looks for main method and invokes it
In Java
7, however, this
does not work anymore, even though it compiles, the following error will
appear when you try to execute it:
The program compiled successfully, but main class was not
found. Main class should contain method: public static void main (String[]
args).
Here an alternative is to write your own launcher,
this way you can define entry points as you want.
In the article JVM
Launcher you will find
the necessary information to get started:
This article explains how we can create a Java Virtual
Machine Launcher (like java.exe or javaw.exe). It explores how the Java Virtual
Machine launches a Java application. It gives you more ideas on the JDK or JRE
you are using. This launcher is very useful in Cygwin (Linux emulator) with
Java Native Interface. This article assumes a basic understanding of JNI.