this.getClass().getClassLoader().getResource("...") 和 NullPointerException [英] this.getClass().getClassLoader().getResource("...") and NullPointerException

查看:55
本文介绍了this.getClass().getClassLoader().getResource("...") 和 NullPointerException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 eclipse helios 中创建了一个带有单个子模块的最小 Maven 项目.

I have created a minimal maven project with a single child module in eclipse helios.

在 src/test/resources 文件夹中,我放置了一个文件install.xml".在文件夹 src/test/java 中,我创建了一个包含单个类的包:

In the src/test/resources folder I have put a single file "install.xml". In the folder src/test/java I have created a single package with a single class that does:

  @Test
  public void doit() throws Exception {
    URL url = this.getClass().getClassLoader().getResource("install.xml");
    System.out.println(url.getPath());

  }

但是当我将代码作为 junit 4 单元测试运行时,我只会得到一个 NullPointerException.这在之前已经运行了一百万次.有什么想法吗?

but when I run the code as a junit 4 unit test I just get a NullPointerException. This has worked fine a million of times before. Any ideas?

我遵循了本指南:

http://www.fuyun.org/2009/11/how-to-read-input-files-in-maven-junit/

但仍然得到同样的错误.

but still get the same error.

推荐答案

使用时

this.getClass().getResource("myFile.ext")

getResource 将尝试查找与包相关的资源.如果您使用:

getResource will try to find the resource relative to the package. If you use:

this.getClass().getResource("/myFile.ext")

getResource 会将其视为绝对路径,并像调用类加载器一样简单地调用类加载器.

getResource will treat it as an absolute path and simply call the classloader like you would have if you'd done.

this.getClass().getClassLoader().getResource("myFile.ext")

不能在 ClassLoader 路径中使用前导 / 的原因是因为所有 ClassLoader 路径都是绝对路径,所以 / 不是路径中的有效第一个字符.

The reason you can't use a leading / in the ClassLoader path is because all ClassLoader paths are absolute and so / is not a valid first character in the path.

这篇关于this.getClass().getClassLoader().getResource("...") 和 NullPointerException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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