Thursday, 9 March 2017

JAVA : WITH OUT MAIN METHOD

JAVA : WITH OUT MAIN METHOD


public class Foo {
    static {
         System.out.println("Message");
         System.exit(0);
    }
}

Use a static initializer block to print the message. This way, as soon as your class is loaded the message will be printed. The trick then becomes using another program to load your class.

Of course, you can run the program as java Foo and you will see the message; however, the command will also fail with a message stating:

Exception in thread "main" java.lang.NoSuchMethodError: main

The System.exit(0) lets the program exit before the JVM is looking for the main method, otherwise the following error will be thrown:

No comments:

Post a Comment