2

I googled a lot but still don't understand Why ClassLoader.getResource("/pkg/readme.txt") always return null? otherwise without the leading slash, ClassLoader.getResource("pkg/readme.txt") can return a correct URL.

I do understand the diff between those methods in Class and ClassLoader.

NOTE: I'm not asking the diff between Class.getResource() and ClassLoader.getResource() because I get it. My concern is on ClassLoader.getResource() does not work for a resource name which starts with a leading slash

Feng Xi
  • 1,005
  • 2
  • 11
  • 30

2 Answers2

3

My concern is on ClassLoader.getResource() does not work for a resource name which starts with a leading slash

That's because there are no resource names that start with a leading slash. By definition a resource name is "a '/'-separated path name that identifies the resource" - the components are separated by slashes, not preceded by them.

someClass.getResource("/pkg/readme.txt") is equivalent to someClass.getClassLoader().getResource("pkg/readme.txt"), the leading slash is not part of the resource name but rather an indication to Class.getResource that it should not prepend the class's package to the path it passes to the classloader. Without the leading slash:

someClass.getResource("pkg/readme.txt")

would be equivalent to

someClass.getClassLoader().getResource("com/example/pkg/readme.txt")

(assuming someClass is in the package com.example)

Ian Roberts
  • 120,891
  • 16
  • 170
  • 183
  • As I said I do understand the diff between Class and ClassLoader.And I do understand what you said. But my question is why ClassLoader.getResource("/pkg/readme.txt") does not work with a leading slash. – Feng Xi Dec 04 '13 at 13:02
  • @FengXi because that's what the language designers decided when they designed this mechanism. You'd have to ask them if you want to know why. There is no resource named `/pkg/readme.txt`, only `pkg/readme.txt` – Ian Roberts Dec 04 '13 at 14:35
2

Class's getResource() - documentation states the difference:

This method delegates the call to its class loader, after making these changes to the resource name: if the resource name starts with "/", it is unchanged; otherwise, the package name is prepended to the resource name after converting "." to "/". If this object was loaded by the bootstrap loader, the call is delegated to ClassLoader.getSystemResource.

What is the difference between Class.getResource() and ClassLoader.getResource()?

Community
  • 1
  • 1
TheEwook
  • 11,037
  • 6
  • 36
  • 55
  • thanks. I'm not asking the diff between Class.getResource() and ClassLoader one. I just want to know why ClassLoader.getResource does not work for a resource name starts with a leading slash. – Feng Xi Dec 04 '13 at 13:04