4

使用 getResourceAsStream 时,我得到一个空指针异常,很少像每 10000 次运行一次。这就是班级的样子

public class ConfigLoader{
  private Properties propies;
  private static ConfigLoader cl = null;
  private ConfigLoader(){
        propies = new Properties;
  }
  public static ConfigLoader getInstance(){
    if(cl == null){
          cl = new ConfigLoader();
    }
  }

  public boolean Load(){
   try{
         propies.load(this.getClass().getResourceAsStream("/config.properties"));          
   }
   catch(NullPointerException e){
         System.out.println("File Does Not Exist");
         return false;
   }
   return true;
   }
}

从这里可以看出,该类是作为单例实现的。该资源显然存在并且大部分时间都可以检测到,但我不确定为什么它偶尔会失败,这对我来说似乎真的很奇怪。

4

1 回答 1

3
  1. 找出什么是 null 会有所帮助(propies?getResourceAsStream 返回的值?)
  2. 我的猜测是您getInstance从多个线程调用,其中一个线程得到一个尚未正确初始化的 ConfigLoader,因为您的单例不是线程安全的

所以我会先通过日志确认,当它失败时,是因为propies为空,如果是这种情况,请让单例线程安全,例如:

private static final ConfigLoader cl = new ConfigLoader;
public static ConfigLoader getInstance() { return cl; }

甚至更好地使用枚举:

public enum ConfigLoader{
  INSTANCE;
  private Properties propies;
  private ConfigLoader(){
    propies = new Properties;
  }

  public static ConfigLoader getInstance(){ return INSTANCE; }

  public boolean Load(){
   try{
         propies.load(this.getClass().getResourceAsStream("/config.properties"));          
   }
   catch(NullPointerException e){
         System.out.println("File Does Not Exist");
         return false;
   }
   return true;
   }
}

或者,如果getResourceAsStream("/config.properties")返回 null,是否可能是由于资源未包含在您的 jar 中而导致的打包问题?

于 2013-09-03T20:13:12.263 回答