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 packagepublic 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.
hm..
ReplyDeleteinteresting...
@vovs, cheers ;)
ReplyDeletewow very useful bit of info. Thx for sharing
ReplyDeleteNote that the code executed in the static initialiser is run in interpred mode (as opposed to JIT).
ReplyDelete@Vyadh, AN interesting point, I have responded with this article Java Secret: Are Static Blocked interpreted?
ReplyDeleteGreat post!
ReplyDeleteOne 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!
@Pedro, you are right it is worth clarifying.
ReplyDeleteThanks Friend
ReplyDeleteThis may have been fixed in JDK 7. Running 1.7.0_11, I get the following:
ReplyDelete$ java Main
Error: Main method not found in class Main, please define the main method as:
public static void main(String[] args)
I suspect you are right. In IntelliJ it doesn't do this with Java 7 update 11 ;)
ReplyDelete