MyClass.class.getClassLoader().getResource(“”).getPath() throws NullPointerException

不羁的心 提交于 2019-12-06 10:43:05

The implementation of getResource is different for different ClassLoader implementations.

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

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).

It's clearly said in the javadocs for the ClassLoader#getResource(String name) method.

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.

Obviously, there is no resource with name "" and therefore null is returned.;

The url is null, so you can't call getPath() on it. Calling getResource with a "" parameter will, at in my understanding always return null, so this is guaranteed to blow up.

getClassLoader public ClassLoader getClassLoader() Returns the class loader for the class. Some implementations may use null to represent the bootstrap class loader. This method will return null in such implementations if this class was loaded by the bootstrap class loader.

Read above lines.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!