Sunday, January 20, 2019

java - How does a method signature of only "static" work?










I have a few years' experience with Java, but I've recently run across something I've never seen before:



public class Project{

...
static{
initDataTypeMapping();
}
...
}


How does this method signature work? Is this in fact even technically a method? I'm wondering why one wouldn't simply put the the method call to initDataTypeMapping() in the constructor. Just trying to increase my understanding so I don't mess something up. Thanks!


Answer




This is known as a static initializer.



The code in the static { } block is run when the class is first loaded by the classloader (which is usually, but not always, when code that refers to the class is first loaded/executed), and is guaranteed to be run in a thread-safe manner.



See this question also.


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...