假设我运行下面的代码
import java.util.ArrayList;
import java.util.List;
public class NoClassDefFoundErrorDueToStaticInitFailure {
public static void main(String args[]) {
System.out.println("Main start");
new User("1");
}
}
class User {
private static String USER_ID = getUserId();
public User(String id) {
this.USER_ID = id;
}
private static String getUserId() {
throw new RuntimeException("UserId Not found");
}
}
它给
Main start
Exception in thread "main" java.lang.ExceptionInInitializerError
at com.NoClassDefFoundError.NoClassDefFoundErrorDueToStaticInitFailure.main(NoClassDefFoundErrorDueToStaticInitFailure.java:10)
Caused by: java.lang.RuntimeException: UserId Not found
at com.NoClassDefFoundError.User.getUserId(NoClassDefFoundErrorDueToStaticInitFailure.java:22)
at com.NoClassDefFoundError.User.<clinit>(NoClassDefFoundErrorDueToStaticInitFailure.java:15)
... 1 more
但是,如果我从上面的 User 类中删除静态并使其如下所示
class User {
private String USER_ID = getUserId();
public User(String id) {
this.USER_ID = id;
}
private String getUserId() {
throw new RuntimeException("UserId Not found");
}
}
堆栈跟踪现在是:
Main start
Exception in thread "main" java.lang.RuntimeException: UserId Not found
at com.NoClassDefFoundError.User.getUserId(NoClassDefFoundErrorDueToStaticInitFailure.java:22)
at com.NoClassDefFoundError.User.<init>(NoClassDefFoundErrorDueToStaticInitFailure.java:15)
at com.NoClassDefFoundError.NoClassDefFoundErrorDueToStaticInitFailure.main(NoClassDefFoundErrorDueToStaticInitFailure.java:10)
由于删除了静态(类级别)关键字,无法理解为什么会发生这种变化