MyClass.class.getClassLoader()。getResource("")。getPath()抛出NullPointerException [英] MyClass.class.getClassLoader().getResource("").getPath() throws NullPointerException

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

问题描述

我的代码在开发计算机上正常运行,但在生产环境中安装时会抛出NullPointerException。抛出异常的行如下:

I have code that is running correctly on a development machine but throws a NullPointerException when installed in a production environment. The line that throws the exception is the following:

MyClass.class.getClassLoader().getResource("").getPath();

所以我把它分成多行代码,看看究竟哪个调用返回null,如下所示:

So I split this into multiple lines of code to see exactly which call was returning null, like this:

ClassLoader cl = MyClass.class.getClassLoader();
URL url = cl.getResource("");
String path = url.getPath();

现在url.getPath()调用抛出NullPointerException,意味着cl.getResource( )返回null。

Now the url.getPath() call is throwing the NullPointerException, meaning that cl.getResource("") is returning null.

有谁能告诉我这个调用怎么会返回null?

Can anyone tell me how this call can ever return null?

推荐答案

对于不同的 ClassLoader 实现, getResource 的实现是不同的。

The implementation of getResource is different for different ClassLoader implementations.

虽然这可能在本地机器上可靠地工作,但不能保证在其他ClassLoader实现上成功。

While this might reliably work on your local machine, it is not guaranteed to be successful on other ClassLoader implementations.

所以期待其他ClassLoader表现不同(特别是如果您在Application Server,WebStart Launcher或任何具有某些安全限制的环境中执行该代码)。

So expect other ClassLoaders to behave differently (especially if you execute that code inside a Application Server, WebStart Launcher or any environment that has some security restrictions).

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

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