[英]getClass() returning null but Foo.class working
When using the following I get a NullPointerException
: 使用以下内容时,我得到一个
NullPointerException
:
Class clazz = Foo.class;
String path = new File(clazz.getClass().getProtectionDomain().getCodeSource().getLocation().toURI().getPath()) + "";
However, it works when I use: 但是,它在我使用时有效:
String path = new File(Foo.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath()) + "";
Is there any way around the NullPointerException
? NullPointerException
有什么办法吗?
You should call getClass()
on an instance of a class. 您应该在类的实例上调用
getClass()
。
MyClass myClassInstance = new MyClass();
Class clazz = myClassInstance.getClass();
You are trying to call it on the class Object 您正在尝试在类Object上调用它
You don't have to invoke getClass on your clazz or you will get the Class.class instead of Foo.class. 您不必在clazz上调用getClass,否则将获得Class.class而不是Foo.class。
So it should be: 因此应该是:
Class clazz = Foo.class;
String path = new File(clazz.getProtectionDomain().getCodeSource().getLocation().toURI().getPath()) + "";
It depends on how the class was loaded - like for instance if the class was loaded from the Bootstrap classloader . 这取决于类的加载方式-例如,如果类是从Bootstrap类加载器加载的 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.