Java独立的代码块

Kas*_*uri 18 java programming-languages

我已经使用Java很长一段时间但从来没有遇到过这样的事情.我想知道它的作用以及为什么它不是错误.

public class Foo{

 private int someVariable;

 {
    doSomething();
 }

 public Foo(){
 }

 private void doSomething(){
    // Something is done here
 }

}
Run Code Online (Sandbox Code Playgroud)

我想知道单个块的目的是什么,其中包含对"doSomething()"的调用.它只是一个骨架代码.我遇到的实际代码是http://www.peterfranza.com/2010/07/15/gwt-scrollpanel-for-touch-screens/

aio*_*obe 28

它是一个(非静态)初始化块.据记载在官方教程在这里:

初始化实例成员

通常,您可以使用代码在构造函数中初始化实例变量.使用构造函数初始化实例变量有两种选择:初始化块和最终方法.实例变量的初始化程序块看起来就像静态初始化程序块,但没有static关键字:

{
    // whatever code is needed for initialization goes here
}
Run Code Online (Sandbox Code Playgroud)

Java编译器将初始化程序块复制到每个构造函数中.因此,该方法可用于在多个构造函数之间共享代码块.


这是一个简单的演示:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

输出:

Initializer block
Constructor 1
---
Initializer block
Constructor 2
Run Code Online (Sandbox Code Playgroud)

例如,在JLabel向面板添加时,您可能会发现这很有用:

panel.add(new JLabel() {{ setBackground(Color.GREEN); setText("Hello"); }});
Run Code Online (Sandbox Code Playgroud)

引擎盖下:

初始化程序块的字节码按字面复制到每个构造函数中.(至少由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
Run Code Online (Sandbox Code Playgroud)

  • 请注意,它在*构造函数代码之前运行*,因此不要依赖于构造函数中完成的事情. (3认同)

lhb*_*oti 7

这是一个初始化块,它被复制到该类的所有构造函数中.