getResourceAsStream returns null pointer exception when using singleton design pattern

StackOverflow https://stackoverflow.com/questions/22155786

  •  19-10-2022
  •  | 
  •  

Question

I was successfully using classLoader.getResourceAsStream until I turned my class into a singleton. Now I'm getting a null pointer exception, but I don't know exactly why changing my class to a singleton would cause the classLoader.getResourceAsStream to throw a null pointer exception.

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
  }

No correct solution

OTHER TIPS

There's no such thing as this when you try to get the resource

Try

static inputStream = ZipCodeCache.classLoader.getResourceAsStream(pathAndFileName)

As @ataylor put it, this returns the class, ZipCodeCache. this.class returns java.lang.Class, and this.class.classLoader returns null

Use this.classLoader, or, i would prefer this, because it is more readable: ZipCodeCache.classLoader

Since you are using a singleton, using 'this' to access the class.classLoader.getResourceAsStream will return null. You must first instantiate the instance and then use the instance to access the class.classLoader. In the code snipping below, Move class.classLoader.getResourceAsStream, down into the loadMaps() method and changed 'this' to '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)

    ...
  } 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top