Java中,关于资源Resource的定位问题

2024-08-30 00:32

本文主要是介绍Java中,关于资源Resource的定位问题,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

通过class的getResource方法,查找与给定类相关的资源

1、class中getResource在JDK中的定义


URL java. lang. Class.getResource( String name)

Finds a resource with a given name. The rules for searching resources associated with a given class are implemented by the definingclass loader of the class. This method delegates to this object's class loader. If this object was loaded by the bootstrap class loader, the method delegates toClassLoader.getSystemResource.

Before delegation, an absolute resource name is constructed from the given resource name using this algorithm:

  • If the name begins with a '/' ('\u002f'), then the absolute name of the resource is the portion of thename following the '/'.
  • Otherwise, the absolute name is of the following form:
       modified_package_name/name

    Where the modified_package_name is the package name of this object with'/' substituted for '.' ('\u002e').

Parameters:
name name of the desired resource
Returns:
A java.net.URL object or null if no resource with this name is found
Since:
JDK1.1

getResource

public URL getResource(String name)
查找带有给定名称的资源。查找与给定类相关的资源的规则是通过定义类的 class loader 实现的。此方法委托给此对象的类加载器。如果此对象通过引导类加载器加载,则此方法将委托给 ClassLoader.getSystemResource(java.lang.String)

在委托前,使用下面的算法从给定的资源名构造一个绝对资源名:

  • 如果 name'/' ('\u002f') 开始,则绝对资源名是 '/' 后面的name 的一部分。
  • 否则,绝对名具有以下形式:
       modified_package_name/name
    

    其中 modified_package_name 是此对象的包名,该名用 '/' 取代了 '.' ('\u002e')。


参数:
name - 所需资源的名称
返回:
一个 URL 对象;如果找不到带有该名称的资源,则返回 null
从以下版本开始:
JDK1.1

getResource方法的实现如下

//getResourcepublic java.net.URL getResource(String name) {name = resolveName(name);ClassLoader cl = getClassLoader0();if (cl==null) {// A system class.return ClassLoader.getSystemResource(name);}return cl.getResource(name);}//resolveNameprivate String resolveName(String name) {if (name == null) {return name;}if (!name.startsWith("/")) {Class c = this;while (c.isArray()) {c = c.getComponentType();}String baseName = c.getName();int index = baseName.lastIndexOf('.');if (index != -1) {name = baseName.substring(0, index).replace('.', '/')+"/"+name;}} else {name = name.substring(1);}return name;}


2、classloader中的getResource在JDK中的定义

URL java. lang. ClassLoader.getResource( String name)

Finds the resource with the given name. A resource is some data (images, audio, text, etc) that can be accessed by class code in a way that is independent of the location of the code.

The name of a resource is a '/'-separated path name that identifies the resource.

This method will first search the parent class loader for the resource; if the parent isnull the path of the class loader built-in to the virtual machine is searched. That failing, this method will invokefindResource(String) to find the resource.

Parameters:
name The resource name
Returns:
A URL object for reading the resource, or null if the resource could not be found or the invoker doesn't have adequate privileges to get the resource.
Since:
1.1

getResource

public URL getResource(String name)
查找具有给定名称的资源。资源是可以通过类代码以与代码基无关的方式访问的一些数据(图像、声音、文本等)。

资源名称是以 '/' 分隔的标识资源的路径名称。

此方法首先搜索资源的父类加载器;如果父类加载器为 null,则搜索的路径就是虚拟机的内置类加载器的路径。如果搜索失败,则此方法将调用 findResource(String) 来查找资源。

参数:
name - 资源名称
返回:
读取资源的 URL 对象;如果找不到该资源,或者调用者没有足够的权限获取该资源,则返回 null
从以下版本开始:
1.1

getResource方法的实现如下

    //getResourcepublic URL getResource(String name) {URL url;if (parent != null) {url = parent.getResource(name);} else {url = getBootstrapResource(name);}if (url == null) {url = findResource(name);}return url;}/*** Find resources from the VM's built-in classloader.*/private static URL getBootstrapResource(String name) {try {// If this is a known JRE resource, ensure that its bundle is // downloaded.  If it isn't known, we just ignore the download// failure and check to see if we can find the resource anyway// (which is possible if the boot class path has been modified).sun.jkernel.DownloadManager.getBootClassPathEntryForResource(name);} catch (NoClassDefFoundError e) {// This happens while Java itself is being compiled; DownloadManager// isn't accessible when this code is first invoked.  It isn't an// issue, as if we can't find DownloadManager, we can safely assume// that additional code is not available for download.}URLClassPath ucp = getBootstrapClassPath();Resource res = ucp.getResource(name);return res != null ? res.getURL() : null;}/*** Finds the resource with the given name. Class loader implementations* should override this method to specify where to find resources.  </p>** @param  name*         The resource name** @return  A <tt>URL</tt> object for reading the resource, or*          <tt>null</tt> if the resource could not be found** @since  1.2*/protected URL findResource(String name) {return null;}



 

3、总结

获取资源是,推荐使用class的getResource方法,它实质上是调用的classloader的getResource方法。

class的getResource方法,对name的路径做了一下解析,

所以,自己没有必要调用classloader的getResource方法(因为它的参数name是有规则要求的,但是在API中没有体现。从类路径下搜索,不能以"/"开头)。

例如:

package org.wsr.spring.demo;public class Demo {public static void main(String[] args) throws Exception {String path = new Demo().getClass().getClassLoader().getResource("").getPath();System.out.println(path);path = new Demo().getClass().getResource("").getPath();System.out.println(path);path = Demo.class.getResource("text.txt").getPath();System.out.println(path);}
}//  output
// /D:/WorkSpace/e_my_work/beantest/target/classes/
// /D:/WorkSpace/e_my_work/beantest/target/classes/org/wsr/spring/demo/
// /D:/WorkSpace/e_my_work/beantest/target/classes/org/wsr/spring/demo/text.txt





这篇关于Java中,关于资源Resource的定位问题的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!


原文地址:
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.chinasem.cn/article/1119290

相关文章

JVisualVM之Java性能监控与调优利器详解

《JVisualVM之Java性能监控与调优利器详解》本文将详细介绍JVisualVM的使用方法,并结合实际案例展示如何利用它进行性能调优,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全... 目录1. JVisualVM简介2. JVisualVM的安装与启动2.1 启动JVisualVM2

Java如何从Redis中批量读取数据

《Java如何从Redis中批量读取数据》:本文主要介绍Java如何从Redis中批量读取数据的情况,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一.背景概述二.分析与实现三.发现问题与屡次改进3.1.QPS过高而且波动很大3.2.程序中断,抛异常3.3.内存消

SpringBoot使用ffmpeg实现视频压缩

《SpringBoot使用ffmpeg实现视频压缩》FFmpeg是一个开源的跨平台多媒体处理工具集,用于录制,转换,编辑和流式传输音频和视频,本文将使用ffmpeg实现视频压缩功能,有需要的可以参考... 目录核心功能1.格式转换2.编解码3.音视频处理4.流媒体支持5.滤镜(Filter)安装配置linu

在Spring Boot中实现HTTPS加密通信及常见问题排查

《在SpringBoot中实现HTTPS加密通信及常见问题排查》HTTPS是HTTP的安全版本,通过SSL/TLS协议为通讯提供加密、身份验证和数据完整性保护,下面通过本文给大家介绍在SpringB... 目录一、HTTPS核心原理1.加密流程概述2.加密技术组合二、证书体系详解1、证书类型对比2. 证书获

Java使用MethodHandle来替代反射,提高性能问题

《Java使用MethodHandle来替代反射,提高性能问题》:本文主要介绍Java使用MethodHandle来替代反射,提高性能问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑... 目录一、认识MethodHandle1、简介2、使用方式3、与反射的区别二、示例1、基本使用2、(重要)

Java实现本地缓存的常用方案介绍

《Java实现本地缓存的常用方案介绍》本地缓存的代表技术主要有HashMap,GuavaCache,Caffeine和Encahche,这篇文章主要来和大家聊聊java利用这些技术分别实现本地缓存的方... 目录本地缓存实现方式HashMapConcurrentHashMapGuava CacheCaffe

SpringBoot整合Sa-Token实现RBAC权限模型的过程解析

《SpringBoot整合Sa-Token实现RBAC权限模型的过程解析》:本文主要介绍SpringBoot整合Sa-Token实现RBAC权限模型的过程解析,本文给大家介绍的非常详细,对大家的学... 目录前言一、基础概念1.1 RBAC模型核心概念1.2 Sa-Token核心功能1.3 环境准备二、表结

eclipse如何运行springboot项目

《eclipse如何运行springboot项目》:本文主要介绍eclipse如何运行springboot项目问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目js录当在eclipse启动spring boot项目时出现问题解决办法1.通过cmd命令行2.在ecl

Java中的Closeable接口及常见问题

《Java中的Closeable接口及常见问题》Closeable是Java中的一个标记接口,用于表示可以被关闭的对象,它定义了一个标准的方法来释放对象占用的系统资源,下面给大家介绍Java中的Clo... 目录1. Closeable接口概述2. 主要用途3. 实现类4. 使用方法5. 实现自定义Clos

Jvm sandbox mock机制的实践过程

《Jvmsandboxmock机制的实践过程》:本文主要介绍Jvmsandboxmock机制的实践过程,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、背景二、定义一个损坏的钟1、 Springboot工程中创建一个Clock类2、 添加一个Controller