public class Test { private int k = printInit("Beetle.k initialized"); int j; public Test() { System.out.println("k = " + k); System.out.println("j = " + j); } private static int x2 = printInit("static Beetle.x2 initialized"); static int printInit(String s) { System.out.println(s); return 47; } public static void main(String[] args) { System.out.println("Beetle constructor"); new Test(); } }
结果:
static Beetle.x2 initialized
Beetle constructor
Beetle.k initialized
k = 47
j = 0
可见访问构造方法时同时也执行了静态初始化,根据《Thinking in Java 4》,类加载和静态成员初始化是等价的,而类加载的触发条件几乎就是but loading also occurs when a static field or static method is accessed.
由此得出:构造方法就是static method了。
另一例:
public class Test1 { static { RuntimeException ex = new RuntimeException(); ex.fillInStackTrace(); ex.printStackTrace(); } public Test1() { throw new RuntimeException(); } public static void main(String[] args) throws Exception { new Test1(); } }
结果:
java.lang.RuntimeException
at Test1.<clinit>(Test1.java:4)
Exception in thread "main" java.lang.RuntimeException
at Test1.<init>(Test1.java:9)
at Test1.main(Test1.java:13)
以上Test1.<init>是发生在 throw new RuntimeException(); 一行,但不清楚实质是否如形式所标示的那样类似一个init静态方法调用,还是暗藏对象对init方法的调用?
因为再看:
public class Test1 { static { RuntimeException ex = new RuntimeException(); ex.fillInStackTrace(); ex.printStackTrace(); } public Test1() { //throw new RuntimeException(); } public void hello() { throw new RuntimeException(); } public static void main(String[] args) throws Exception { Test1 t = new Test1(); t.hello(); } }
结果:
java.lang.RuntimeException
at Test1.<clinit>(Test1.java:4)
Exception in thread "main" java.lang.RuntimeException
at Test1.hello(Test1.java:13)
at Test1.main(Test1.java:18)
非静态方法hello抛异常的表示形式也是如此 类名.方法名