Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
202 views
in Technique[技术] by (71.8m points)

java - Class.getResource and ClassLoader.getSystemResource: is there a reason to prefer one to another?

I saw both Class.getResource and ClassLoader.getSystemResource used to locate a resource in Java. Is there any reason to prefer one to another?

question from:https://stackoverflow.com/questions/6298400/class-getresource-and-classloader-getsystemresource-is-there-a-reason-to-prefer

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There are several ways to load resources, each with a slightly different meaning -

ClassLoader::getSystemResource() uses the system classloader. This uses the classpath that was used to start the program. If you are in a web container such as tomcat, this will NOT pick up resources from your WAR file.

Class<T>#getResource() prepends the package name of the class to the resource name, and then delegates to its classloader. If your resources are stored in a package hierarchy that mirrors your classes, use this method.

ClassLoader#getResource() delegates to its parent classloader. This will eventually search for the resource all the way upto the system classloader.

If you are confused, just stick to ClassLoader#getResource()


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...