在我的Android应用程序中,我必须在第一个Activity开始之前初始化很多静态对象。据我所知,静态变量是在类加载时初始化的。因此,随着时间的流逝,项目中静态对象的数量开始增长,现在我得到了NullPointerExceptions。就我而言,静态对象可以在其构造函数中调用其他静态对象。所以我的问题是:是否可以在某些静态变量依赖于变量之前初始化它们,从而导致NullPointersExceptions?那可能吗? 代码示例:
private static class HardwareManagersHolder implements HardwareManagers, IManagers {
private final AtomicBoolean senderAcquire = new AtomicBoolean(false);
private final AtomicInteger receiverAcquire = new AtomicInteger(0);
public IAudioManager audioManager;
public IVideoManager videoManager;
public IVibrationManager vibrationManager;
public IBatteryHelper batteryHelper;
@Override
public void configureManager() {
audioManager = AudioHelper.getInstance();
vibrationManager = VibrationManager.getInstance();
videoManager = VideoManager.getInstance();
batteryHelper = BatteryHelper.getInstance();
}
还有一个对象架:
public class VideoManager implements IVideoManager {
private static class VideoManagerHolder {
public static final VideoManager VIDEO_MANAGER_INSTANCE = new VideoManager();
}
public static VideoManager getInstance() {
return VideoManagerHolder.VIDEO_MANAGER_INSTANCE;
}
}
答案 0 :(得分:1)
我尝试使用您提供的代码段重构您的异常。我使用了以下代码:
public interface IVideoManager {}
public class VideoManager implements IVideoManager {
private static class HardwareManagersHolder {
public IVideoManager videoManager;
public void configureManager() {
videoManager = VideoManager.getInstance();
}
}
private static class VideoManagerHolder {
public static final VideoManager VIDEO_MANAGER_INSTANCE = new VideoManager();
}
public static VideoManager getInstance() {
return VideoManagerHolder.VIDEO_MANAGER_INSTANCE;
}
public static void main(String[] arg) {
System.out.println("Start test");
HardwareManagersHolder h = new HardwareManagersHolder();
h.configureManager();
if (h.videoManager == null) {
System.out.println("VideoManager is null");
}
System.out.println("Test finished");
}
}
此代码可在我的计算机上使用。如果此代码对您不起作用,则还有其他错误。
答案 1 :(得分:0)
您是否在静态构造函数中初始化它们?正是由于这个原因,他们会首先被致电。
static
{
VIDEO_MANAGER_INSTANCE = new VideoManager();
}