Java:静态初始化块什么时候有用?

Ada*_*tan 69 java static-initialization

static块内初始化有什么区别:

public class staticTest {

    static String s;
    static int n;
    static double d;

    static {
        s = "I'm static";
        n = 500;
        d = 4000.0001;
    }
    ...
Run Code Online (Sandbox Code Playgroud)

和个人静态初始化:

public class staticTest {

    static String s = "I'm static";
    static int n    = 500;
    static double d = 4000.0001;

    ....
Run Code Online (Sandbox Code Playgroud)

Ric*_*lly 83

静态初始化块允许更复杂的初始化,例如使用条件:

static double a;
static {
    if (SomeCondition) {
      a = 0;
    } else {
      a = 1;
    }
}
Run Code Online (Sandbox Code Playgroud)

或者,当不仅仅需要构造时:使用构建器来创建实例时,除了创建静态字段之外,还需要进行异常处理或工作.

静态初始化块也在内联静态初始化程序之后运行,因此以下内容有效:

static double a;
static double b = 1;

static {
    a = b * 4; // Evaluates to 4
}
Run Code Online (Sandbox Code Playgroud)

  • 做"b = a*4;" 如果在a之前声明了b,则内联只会是一个问题,在你的例子中并非如此. (2认同)

gaw*_*awi 16

典型用法:

private final static Set<String> SET = new HashSet<String>();

static {
    SET.add("value1");
    SET.add("value2");
    SET.add("value3");
}
Run Code Online (Sandbox Code Playgroud)

没有静态初始化程序,你会怎么做?

  • 答案:[Guava](http://guava-libraries.googlecode.com/svn/trunk/javadoc/com/google/common/collect/ImmutableMap.Builder.html) :) +1 (2认同)
  • 另一个没有额外库的答案:创建一个静态方法来封装`SET`的初始化并使用变量初始化器(`private final static Set&lt;String&gt; SET = createValueSet()`)。如果您有 5 个集合和 2 个地图,您会将它们全部转储到一个 `static` 块中吗? (2认同)

Pau*_*ora 10

初始化期间的异常处理是另一个原因.例如:

static URL url;
static {
    try {
        url = new URL("https://blahblah.com");
    }
    catch (MalformedURLException mue) {
        //log exception or handle otherwise
    }
}
Run Code Online (Sandbox Code Playgroud)

这对于烦人地抛出已检查异常的构造函数(如上所述)或者可能容易出现异常的更复杂的初始化逻辑非常有用.


Mic*_*ael 9

我们使用构造函数有条件地初始化实例变量。

如果你想有条件地初始化类/静态变量,并且想在不创建对象的情况下完成它(构造函数只能在创建对象时调用),那么你需要静态块。

static Scanner input = new Scanner(System.in);
static int widht;
static int height;

static
{
    widht = input.nextInt();
    input.nextLine();
    height = input.nextInt();
    input.close();

    if ((widht < 0) || (height < 0))
    {
        System.out.println("java.lang.Exception: Width and height must be positive");
    }
    else
    {
        System.out.println("widht * height = " + widht * height);
    }
}
Run Code Online (Sandbox Code Playgroud)


Jes*_*per 5

有时您想做的不仅仅是为静态变量赋值.由于您不能在类体中放置任意语句,因此可以使用静态初始化程序块.


小智 5

您可以在内部使用try / catch块,static{}如下所示:

MyCode{

    static Scanner input = new Scanner(System.in);
    static boolean flag = true;
    static int B = input.nextInt();
    static int H = input.nextInt();

    static{
        try{
            if(B <= 0 || H <= 0){
                flag = false;
                throw new Exception("Breadth and height must be positive");
            }
        }catch(Exception e){
            System.out.println(e);
        }

    }
}
Run Code Online (Sandbox Code Playgroud)

PS:从这里引用!