静态块是否按顺序执行?如果它不是块怎么办

Are static blocks executed in sequential order? Also what if it isn't a block

这些带有静态初始值设定项的行是否保证按顺序 运行?因为否则事情可能会出错

public Class x {
    private static final BasicDataSource ds = new BasicDataSource();
    private static final JdbcTemplate jdbcTemplate = new JdbcTemplate(ds);
    private static final SomeDao someDao = new SomeDao(jdbcTemplate);
}

好的...这个怎么样?

public Class x {
    private static final BasicDataSource ds;
    private static final JdbcTemplate jdbcTemplate;
    private static final SomeDao someDao;

    static {
        ds = new BasicDataSource();
        ds.setStuff("foo");
        ds.setAnotherProperty("bar");
        jdbcTemplate = new JdbcTemplate(ds);
        SomeDao someDao = new SomeDao(jdbcTemplate);
    }
}

它们将按照与它们在源代码中列出的方式相对应的顺序执行。

A class can have any number of static initialization blocks, and they can appear anywhere in the class body. The runtime system guarantees that static initialization blocks are called in the order that they appear in the source code. Initializing Fields

这可以在以下代码中观察到:

private static A a1 = new A(0);
private static A a2 = new A(1);
private static A a3 = new A(2);
private static A a4 = new A(3);
private static A a5 = new A(4);
private static A a6 = new A(5);

public static void main (String args[]) {  }

static class A {
    public A (int a) {
        System.out.print(a);
    }
}

输出为总是 012345.