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.

Comments

  1. wow very useful bit of info. Thx for sharing

    ReplyDelete
  2. Note that the code executed in the static initialiser is run in interpred mode (as opposed to JIT).

    ReplyDelete
  3. @Vyadh, AN interesting point, I have responded with this article Java Secret: Are Static Blocked interpreted?

    ReplyDelete
  4. Great post!

    One remark though. You said that:

    "The Instrumentation class gives the agent access to each class' byte code BEFORE it is loaded"

    I firstly heard about Java Agents after reading your post, but as I understand it, the Agent runs AFTER loading the class but BEFORE the linking occurs.

    [http://java.sun.com/docs/books/jvms/second_edition/html/Concepts.doc.html#19042]

    Cheers!

    ReplyDelete
  5. @Pedro, you are right it is worth clarifying.

    ReplyDelete
  6. This may have been fixed in JDK 7. Running 1.7.0_11, I get the following:

    $ java Main
    Error: Main method not found in class Main, please define the main method as:
    public static void main(String[] args)

    ReplyDelete
  7. I suspect you are right. In IntelliJ it doesn't do this with Java 7 update 11 ;)

    ReplyDelete

Post a Comment

Popular posts from this blog

Java is Very Fast, If You Don’t Create Many Objects

System wide unique nanosecond timestamps

Unusual Java: StackTrace Extends Throwable