sproketboy
sproketboy

Reputation: 9452

getResourceAsStream class vs getClass()

I'm maintaining a piece of code and I'm not sure of a condition.

resourceStream = StorageEngine.class.getResourceAsStream(resourceFile);
if (resourceStream == null) {
    log.info("StorageEngine: didn't find  resource file in the classes root ");
    resourceStream = this.getClass().getResourceAsStream(resourceFile);
}

Is there really a difference between StorageEngine.class.getResourceAsStream and this.getClass().getResourceAsStream ?

TIA

Upvotes: 1

Views: 351

Answers (2)

parsifal
parsifal

Reputation: 296

Short answer: yes, but neither are really the right way to do this.

Long answer: different classes may be loaded by different classloaders, each of which has access to a different set of files. If StorageClass and this were loaded by different classloaders, then it's entirely possible that one call will return null while the other succeeds.

The best all-around approach is the following:

Thread.currentThread().getContextClassLoader().getResourceAsStream("/absolute_path");

In a simple packaged application, some people consider this overkill. Where it's really useful is in a web-app, where different parts of the application may be loaded by different classloaders.

The only time, IMO, that you should load using an explicit class is when you're writing library code and want to ensure that you're getting your copy of a particular resource. That situation is extremely rare; normally a library wants to use resources packaged by the application.

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500055

Is there really a difference between StorageEngine.class.getResourceAsStream and this.getClass().getResourceAsStream ?

Yes, absolutely.

  • If the resource name is a relative one, it will be relative to the package containing the relevant class
  • If the two classes are in different classloaders, one may be able to access a resource and the other not

Of course if this is an instance of StorageEngine (and not a subclass) then they really are equivalent.

Upvotes: 1

Related Questions