First, Introduction
To tell the truth, this part of the knowledge in the initial learning of C # Foundation of the time learned, at first remember that there is such a thing, and then learn Java for the foundation to jump past a lot, the recent project encountered a problem, of course, the final problem solved, resolved to think of the class in the module load order this knowledge point, When the results and theory at this time mutually confirm, to this knowledge enlightened, also clearer.
Second, the origin of the problem
A class test is given to spring for management, but this class is configured in XML, and @autowired is injected into the test class using the @service annotation call,private call, I used a call method in the Test class constructor, the result of a null pointer problem, at first my idea is that the class through the XML configuration can not use the class using annotations, but later think and feel certainly not so ah, 2 ways can certainly be used together Ah, debugging found the reason: A constructor is a module that is first executed in a class, except for a static resource part. Other non-static modules must be initialized after him, so calling other non-static resources in the constructor will definitely report a null pointer exception.
Iii. Examples and explanations
Here is a little demo that I wrote after simplifying the problem to prove each other:
1. A common Java class Person,animal class
Public class Person { public person () { System.out.println ("Initialized Peron class");} }
Public class Animal { public Animal () { System.out.println ("Animao run ...");} }
2. A man class that references a person.
Public class The man { static { System.out.println... "); } Private New Person (); Private Static New Animal (); Public Man () { System.out.println ("3. The man constructor runs ... "); }}
It contains: Static method blocks (static constructors with C #), global variables, constructors.
3. Calling the Man class
Public class MyTest { publicstaticvoid main (string[] args) { mansman = New man ();} }
Iv. Results and conclusions
Think the results would be God's horse?
Ideas:
1. Static variables are global, so they must be initialized first, followed by non-static ones.
2. Constructor precedence global variable.
So the order after execution should be
1. static method Block 2. Static global variable 3. Constructor 4. Non-static global variables
The load order of the modules in the
class