我已经使用 Java 很长时间了,但从来没有遇到过这样的事情。
我想知道它的作用以及为什么它不是错误。
public class Foo{
private int someVariable;
{
doSomething();
}
public Foo(){
}
private void doSomething(){
// Something is done here
}
}
我想知道包含对“doSomething()”的调用的单个 block 的用途是什么。
它只是一个骨架代码。我遇到的实际代码位于 http://www.peterfranza.com/2010/07/15/gwt-scrollpanel-for-touch-screens/
这是一个(非静态)初始化 block 。官方教程中有记载here :
Initializing Instance Members
Normally, you would put code to initialize an instance variable in a constructor. There are two alternatives to using a constructor to initialize instance variables: initializer blocks and final methods.
Initializer blocks for instance variables look just like static initializer blocks, but without the static keyword:
{
// whatever code is needed for initialization goes here
}
The Java compiler copies initializer blocks into every constructor. Therefore, this approach can be used to share a block of code between multiple constructors.
这是一个简单的演示:
public class Test {
{
System.out.println("Initializer block");
}
Test() {
System.out.println("Constructor 1");
}
Test(int i) {
System.out.println("Constructor 2");
}
public static void main(String[] args) {
new Test();
System.out.println("---");
new Test(1);
}
}
输出:
Initializer block
Constructor 1
---
Initializer block
Constructor 2
例如,将 JLabel
添加到面板时,您可能会发现这很有用:
panel.add(new JLabel() {{ setBackground(Color.GREEN); setText("Hello"); }});
引擎盖下:
初始化 block 的字节码被逐字复制到每个构造函数中。 (至少 Suns javac 和 eclipse 编译器是这样的:
Test();
Code:
0: aload_0
1: invokespecial
4: getstatic #2;
7: ldc #3; //String "Initializer block"
9: invokevirtual #4; //Method PrintStream.println:(String;)V
12: getstatic #2;
15: ldc #5;
17: invokevirtual #4;
20: return
Test(int);
Code:
0: aload_0
1: invokespecial #1;
4: getstatic #2;
7: ldc #3; //String "Initializer block"
9: invokevirtual #4; //Method PrintStream.println:(String;)V
12: getstatic #2;
15: ldc #6;
17: invokevirtual #4;
20: return