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

后端 未结 4 2090
借酒劲吻你
借酒劲吻你 2020-12-04 16:40

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

4条回答
  •  伪装坚强ぢ
    2020-12-04 17:19

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

提交回复
热议问题