Class.getResource和ClassLoader.getSystemResource:是否有理由相互选择? [英] Class.getResource and ClassLoader.getSystemResource: is there a reason to prefer one to another?

查看:89
本文介绍了Class.getResource和ClassLoader.getSystemResource:是否有理由相互选择?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到 Class.getResource ClassLoader.getSystemResource 用于在Java中查找资源。是否有理由更喜欢彼此?

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

推荐答案

有几种方法可以加载资源,每种资源的含义略有不同 -

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

ClassLoader :: getSystemResource()使用系统类加载器。这使用用于启动程序的类路径。如果您在诸如tomcat之类的Web容器中,则不会从WAR文件中获取资源。

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( )将类的包名称添加到资源名称,然后委托给它的类加载器。如果资源存储在镜像类的包层次结构中,请使用此方法。

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()委托给其父类加载器。这将最终搜索资源一直到系统类加载器。

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

如果您感到困惑,只需坚持 ClassLoader#getResource()

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

这篇关于Class.getResource和ClassLoader.getSystemResource:是否有理由相互选择?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆