这个错误是说变量初始化出现问题,通常出现在静态变量尤其是单例模式。这种问题往往是初始化顺序不对造成的,下面举个简单的例子。
[java] view plainco
import java.util.HashMap;
import java.util.Map;
public class Example {
private static Example example = new Example();
private static Map<Integer,Boolean> test =
new HashMap<Integer, Boolean>();
private Example()
{
test.put(1, true);
}
public static Example getInstance()
{
return example;
}
}
如果你在别的类调用getInstance,就会报错ExceptionInInitializerError。这是因为类加载时不会为实例变量赋值,对象创建时不会为静态变量赋值。我们调用getInstance时,此类就开始加载,加载的时候不会为实例变量赋值,但是会按顺序给静态变量赋值,所以先为example赋值,然后为test赋值即初始化。但为example赋值时出现了个小插曲,它会调用构造方法创建一个对象。对象创建时不会为静态变量test赋值,而构造器内却已经调用test,于是报错了。
改为:
[java] view plaincopy
private static Map<Integer,Boolean> test =
new HashMap<Integer, Boolean>();
private static Example example = new Example();
就可以了
但是在实际的开发中,可能会遇到如下的bug:
java.lang.ExceptionInInitializerError
at com.tencent.connect.auth.QQAuth.createInstance(ProGuard:54)
at com.tencent.tauth.Tencent.(ProGuard:49)
at com.tencent.tauth.Tencent.createInstance(ProGuard:59)
at cn.app.activity.news.News_Login.onCreate(News_Login.java:93)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1149)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1792)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1847)
at android.app.ActivityThread.access$1500(ActivityThread.java:176)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1040)
at android.os.Handler.dispatchMessage(Handler.java:130)
at android.os.Looper.loop(Looper.java:384)
at android.app.ActivityThread.main(ActivityThread.java:3971)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:538)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:978)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:732)
at dalvik.system.NativeStart.main(Native Method)
这是在引用其他jar包时出现的错误,怎么办呢?最好的解决办法就是加try catch。
来源:oschina
链接:https://my.oschina.net/u/1244156/blog/232828