使用单例设计模式时,getResourceAsStream返回空指针异常

时间:2014-03-03 19:41:44

标签: groovy singleton

我成功使用了classLoader.getResourceAsStream,直到我将我的类变成了单例。现在我得到一个空指针异常,但我不知道为什么将我的类更改为单例会导致classLoader.getResourceAsStream抛出空指针异常。

class ZipCodeCache {
  static pathAndFileName = 'com/generator/data/ZipCode.txt'
  static inputStream = this.class.classLoader.getResourceAsStream(pathAndFileName)

  private static volatile instance
  private ZipCodeCache() {}

  static ZipCodeCache getInstance(){
    if (instance) {
      return instance
    } else {
      synchronized(ZipCodeCache) {
        if (instance) {
          instance
        } else {
          instance = new ZipCodeCache()
          loadMaps()
        }
      }
    }

    return instance
  }

3 个答案:

答案 0 :(得分:3)

当你试图获取资源

时,没有this这样的东西

尝试

static inputStream = ZipCodeCache.classLoader.getResourceAsStream(pathAndFileName)

答案 1 :(得分:0)

正如@ataylor所说,这将返回类ZipCodeCache。 this.class返回java.lang.Class,this.class.classLoader返回null

使用this.classLoader,或者,我更喜欢这个,因为它更具可读性:ZipCodeCache.classLoader

答案 2 :(得分:0)

由于您使用的是单例,因此使用“this”访问class.classLoader.getResourceAsStream将返回null。您必须首先实例化实例,然后使用该实例访问class.classLoader。在下面的代码片段中,将class.classLoader.getResourceAsStream移动到loadMaps()方法中,并将'this'更改为'instance'。

class ZipCodeCache {
  static pathAndFileName = 'com/generator/data/ZipCode.txt'

  private static volatile instance
  private ZipCodeCache() {}

  static ZipCodeCache getInstance(){
    if (instance) {
      return instance
    } else {
      synchronized(ZipCodeCache) {
        if (instance) {
          instance
        } else {
          instance = new ZipCodeCache()
          loadMaps()
        }
      }
    }

    return instance
  }

  private static loadMaps() {
    def inputStream = instance.class.classLoader.getResourceAsStream(pathAndFileName)

    ...
  }