简体   繁体   中英

getClass() returning null but Foo.class working

When using the following I get a 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 ?

You should call getClass() on an instance of a class.

MyClass myClassInstance = new MyClass();
Class clazz = myClassInstance.getClass();

You are trying to call it on the class Object

You don't have to invoke getClass on your clazz or you will get the Class.class instead of 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 .

See here for a more complete answer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM