Tuesday, July 9, 2013

Java Secret: What is called before main.

Overview

The starting point for core java applications is the main(String[]) method. But is there any code which is called before this method and do we even need it?

The class has to be initialised

Before calling main, the static block for the class is called to initialise the class.

public class Main {
    static {
        System.out.println("Called first.");
    }
    public static void main(String... args) {
        System.out.println("Hello world.");
    }
}
prints
Called first.
Hello world.

Can we avoid having a main()

Normally, if you don't have a main() method, you will get an error. However if your program exits before calling main() no error is produced.
public class Main {
    static {
        System.out.println("Hello world.");
        System.exit(0);
    }
}
prints
Hello world.

The premain method

If you have Java agents, those agents can have a premain method which is called first. Instrument package

public static void premain(String agentArgs, Instrumentation inst);
The Instrumentation class gives the agent access to each class' byte code after it is read and before it is linked, giving the agent the option to change byte code.

One interesting feature of the Instrumentation class is the getObjectSize() which will give you the size of an object.

No comments: