In this NotePadProvider sample code, I noticed that inside the class there is a static block without any name and without any type:
static {
sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
sUriMatcher.addURI(NotePad.AUTHORITY, "notes", NOTES);
sUriMatcher.addURI(NotePad.AUTHORITY, "notes/#", NOTE_ID);
sUriMatcher.addURI(NotePad.AUTHORITY, "live_folders/notes", LIVE_FOLDER_NOTES);
sNotesProjectionMap = new HashMap<String, String>();
sNotesProjectionMap.put(NoteColumns._ID, NoteColumns._ID);
sNotesProjectionMap.put(NoteColumns.TITLE, NoteColumns.TITLE);
sNotesProjectionMap.put(NoteColumns.NOTE, NoteColumns.NOTE);
sNotesProjectionMap.put(NoteColumns.CREATED_DATE, NoteColumns.CREATED_DATE);
sNotesProjectionMap.put(NoteColumns.MODIFIED_DATE, NoteColumns.MODIFIED_DATE);
// Support for Live Folders.
sLiveFolderProjectionMap = new HashMap<String, String>();
sLiveFolderProjectionMap.put(LiveFolders._ID, NoteColumns._ID + " AS " +
LiveFolders._ID);
sLiveFolderProjectionMap.put(LiveFolders.NAME, NoteColumns.TITLE + " AS " +
LiveFolders.NAME);
// Add more columns here for more robust Live Folders.
}
What does this static { } mean?
Also, what is the advantage of using this terse syntax over a more readable syntax (I am only assuming such one exists, I don’t know that for sure until the first question is answered).
That is the static initializer of the class. It is executed only once. When? The first time you ever use that class in your application.
The idea is to construct some variables, structures, data, etc… (whatever you like) that will be used across all the instances of that class. Or, for example, simply construct a lookup table for sine values.
There are several ways it gets invoked. All of these situations:
new MyClass();first calls the static initializer and then the constructorClass.forName("my.package.MyClass");MyClass.staticMethodCallHere();MyClass.class.methodCallHere();