Meaning of new Class(...){{...}} initialization idiom
This question already has an answer here:
It's called double curly brace initialization. (EDIT: Link removed, archived here)
It means you're creating an anonymous subclass and the code within the double braces is basically a constructor. It's often used to add contents to collections because Java's syntax for creating what are essentially collection constants is somewhat awkward.
So you might do:
List<String> list = new ArrayList<String>() {{
add("one");
add("two");
add("three");
}};
instead of:
List<String> list = new ArrayList<String>();
list.add("one");
list.add("two");
list.add("three");
I actually don't like that and prefer to do this:
List<String> list = Arrays.asList("one", "two", "three");
So it doesn't make much sense in that case whereas it does for, say, Maps, which don't have a convenient helper.
The "outer" braces mean that you're making an anonymous subclass, the second braces are the object initializer. The initializer is run before the class' constructor, but after any super
calls (and therefore also after any superclass initializers). You can use initializers in non-anonymous classes, too, which is a convenient way to initiate final
fields if you have several constructors which cannot call each other, or fields which need more complex initialization than usual field initializers allow.
Consider this class:
class X extends Y{
private final int lulz;
private static boolean someCondition(){...}
private static boolean danger() throws SomeException { ... }
public X(A a) throws SomeException {
super(a);
lulz = someCondition()? danger() : 0;
}
public X(B b) throws SomeException {
super(b);
lulz = someCondition()? danger() : 0;
}
}
It could be rewritten as:
class X extends Y{
private final int lulz;
private static boolean someCondition(){...}
private static boolean danger() throws SomeException { ... }
{ // initalizer -- might throw SomeException!
lulz = someCondition()? danger() : 0;
}
public X(A a) throws SomeException { super(a); }
public X(B b) throws SomeException { super(b); }
}
If the initializer can throw a checked exception, all constructors must declare they can throw it.
您正在创建一个匿名类并使用类Instance initializer idiom,如下所示:
class X {
private Y var1;
private X() {
Z context = new Z(
new SystemThreadPool()) {
{ // This is the initialize idiom
var1 = new Y(); //
} //
}
); // BTW you are missing ")"
}
}
链接地址: http://www.djcxy.com/p/23982.html
上一篇: 如何在Java中使用Class <T>?