java.lang.ExceptionInInitializerError的解决方法

早过忘川 提交于 2019-12-01 22:31:03

 这个错误是说变量初始化出现问题,通常出现在静态变量尤其是单例模式。这种问题往往是初始化顺序不对造成的,下面举个简单的例子。

[java] view plainco

  1. import java.util.HashMap;  

  2. import java.util.Map;  

  3.   

  4. public class Example {  

  5.   

  6.     private static Example example = new Example();  

  7.       

  8.     private static Map<Integer,Boolean> test =   

  9.         new HashMap<Integer, Boolean>();  

  10.       

  11.     private Example()  

  12.     {  

  13.         test.put(1true);  

  14.     }  

  15.       

  16.     public static Example getInstance()  

  17.     {  

  18.         return example;  

  19.     }  

  20. }  

      如果你在别的类调用getInstance,就会报错ExceptionInInitializerError。这是因为类加载时不会为实例变量赋值,对象创建时不会为静态变量赋值。我们调用getInstance时,此类就开始加载,加载的时候不会为实例变量赋值,但是会按顺序给静态变量赋值,所以先为example赋值,然后为test赋值即初始化。但为example赋值时出现了个小插曲,它会调用构造方法创建一个对象。对象创建时不会为静态变量test赋值,而构造器内却已经调用test,于是报错了。

改为:

[java] view plaincopy

  1. private static Map<Integer,Boolean> test =   

  2.         new HashMap<Integer, Boolean>();  

  3. 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。


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!