Sunday 14 April 2019

java - Android:I do not understand: static { foo();}




Sometimes I see something like it, in a class in Android:




static
{
foo();
}



  • What does this do?


  • Why?




Answer



That's a static block. It is executed the first time that class is referenced on your code, and it is calling a static method called foo(). You can find more about the static block here. As mentioned by @CommonsWare, you can initialize a static field in two different ways, inline a declaration time



static ArrayList test = new ArrayList() {{
add("A");
add("B");
add("C");
}};



but as you can see it is not easy to read. If you use a static block instead



  static ArrayList test;
static {
test = new ArrayList<>();
test.add("a");
test.add("b");
test.add("c");
}



or as in your question have



static ArrayList test;
static {
foo();
}

private static void foo() {
test = new ArrayList<>();

test.add("a");
test.add("b");
test.add("c");
}

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...