getClass().getResource()和classLo

2019-03-16  本文已影响0人  我有一只喵喵

一、getClass().getResource(String name)

javadoc解释: Finds a resource with a given name. If the {@code name} begins with a {@code '/'}, then the absolute name of the resource is the portion of the {@code name} following the {@code '/'}. Otherwise, the absolute name is of the following form:

该api用来获取指定给定名称的资源,返回java.net.URL对象,如果找不到资源则返回null。在这里name有以“/”开始和不以“/开始”的区别,下面有具体代码来解释。

测试类结构
        System.out.println(this.getClass().getResource(""));
        System.out.println(this.getClass().getResource("/"));

        //输出
      file:/E:/activitistudy/activiti_spring/target/classes/cn/cf/
      file:/E:/activitistudy/activiti_spring/target/classes/

可以看到如果不以/开头,那么是从当前类的位置去寻找资源,否则是从classpath下去寻找资源

二、classLoader.getResource(String name)

javadoc解释: 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.

查找具有给定名称的资源。资源是一些数据(图像、音频、文本等),类代码可以以独立于代码位置的方式访问这些数据。 这种方法首先查找自己的父亲ClassLoader,由自己的父ClassLoader来查找资源(实际上, 假设父亲的父亲不是空, 则父亲仍会向上提交查找请求). 假设自己的父ClassLoader是null, 则查找Java虚拟机中内建的class loader, 并将资源请求提交给它们, 假设这些操作都失败了, 则ClassLoader会调用自己的findResource()方法来查找资源.

注意: classLoader.getResource(String name)中的name不能以/开头。因为就是从classpath根路径去加载的,看以下代码:

        System.out.println(Test.class.getClassLoader().getResource(""));
        System.out.println(Test.class.getClassLoader().getResource("/"));
        
        //输出结果
        file:/E:/activitistudy/activiti_spring/target/classes/
        null
还有一个方式是classLoad.getResources(String name),该方法是返回一个Enumeration<URL>,它与getResource的区别是,getResource()方法会返回类路径上碰到的第一个资源。 而getResources()则会返回当前类载入器路径上的全部反复资源以及父类载入器上的全部反复资源。
上一篇 下一篇

猜你喜欢

热点阅读