Class. forName () + Class. forName (). newlnstance () and the relationship between the new statement and the initialization block + static initialization block + constructor,
Code first
Class A {int a; static {System. out. println ("executed when loading the class");} public A () {System. out. println ("Although I wrote it before the initialization block, but the actual content in the initialization block is executed before I");} {System. out. println ("Run me first! ") ;}} Public class Html {public static void main (String [] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException {Class O = Class. forName ("A"); Class P = Class. forName ("A"); O. newInstance (); A I = new A (); A o = new ();}}
The code execution result is
Executed when loading a class
Run me first!
Although I wrote it before the initialization block, I actually executed the content in the initialization block before executing me.
Run me first!
Although I wrote it before the initialization block, I actually executed the content in the initialization block before executing me.
Run me first!
Although I wrote it before the initialization block, I actually executed the content in the initialization block before executing me.
References
Http://www.cnblogs.com/xingzc/p/5760166.html
Http://www.cnblogs.com/wangxin37/p/6397742.html
Newlnstance () is a method
New is a keyword.
The use of newlnstance () in Class is limited. He can only call constructors without parameters.
The new Keyword generation object (class instance) does not have this restriction
Class .. forName () returns a Class
Class. forName (). newlnstance () returns the Object (instance of the Class)
Initialization Block
Same as the constructor, it is used to initialize objects (assign values );
An initialization block is enclosed by curly brackets in the class.
Its function is to place it at the beginning of each constructor in the class.
Static initialization Block
The difference between the block construction and the Declaration is that the declaration contains STATIC, and the other is the same as the initialization block. When the class is loaded, only static members can be referenced.