【问题标题】:this.getClass().getClassLoader().getResource("").getPath() is NPE possible here?this.getClass().getClassLoader().getResource("").getPath() 这里可以使用 NPE 吗?
【发布时间】:2023-03-21 05:29:01
【问题描述】:

我得到了代码审查评论,下面一行可以返回NPE

this.getClass().getClassLoader().getResource("").getPath()

当我提到自我课程时,我有没有机会得到NPE

我找到了this answer,它说如果我加载外部文件,那么就有NPE 的可能性,对吗?

【问题讨论】:

  • getResource("") -> 不确定,但我想可以。
  • 你能回答一下为什么吗?我该如何克服它?对我很有好处。
  • 你可以添加一个简单的空检查
  • 术语“资源(名称)”受类加载器实现的约束。在默认系统类加载器和URLClassLoader 下,当加载器的搜索路径未指定或不包含任何目录条目时,getResource("") 实际上将返回null。其他一些加载器可能更愿意无条件返回null 或将特殊语义附加到空资源名称或其他任何内容。
  • 最好的机会是使用System.getProperty("java.class.path"),或者,如果适用(JDK ((URLClassLoader) ClassLoader.getSystemClassLoader()).getURLs()。但在一般情况下,永远不能 100% 保证它不会返回 null,因为它最终取决于启动 JVM 的内容/方式。

标签: java classloader absolute-path file-location


【解决方案1】:

我使用下面的代码来避免NPE

Paths.get("").toAbsolutePath().normalize().toString()

是的,从评论来看,这个 JavaDoc 很有帮助。

https://docs.oracle.com/javase/7/docs/api/java/lang/ClassLoader.html#getResource(java.lang.String)

getResource
public URL 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 is null the path of the class loader built-in to the virtual machine is searched. That failing, this method will invoke findResource(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

【讨论】:

    猜你喜欢
    • 2011-04-17
    • 1970-01-01
    • 2015-04-13
    • 1970-01-01
    • 2013-06-06
    • 2015-06-03
    • 1970-01-01
    • 2010-10-12
    • 1970-01-01
    相关资源
    最近更新 更多