简体   繁体   中英

why ClassLoader.getResource(“/pkg/readme.txt”) always return null with resource name with a leading slash?

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

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 )

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()?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM