0

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?

tank
  • 11
  • 4

3 Answers3

3

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

TheLostMind
  • 35,966
  • 12
  • 68
  • 104
1

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()) + "";
Stefaan Neyts
  • 2,054
  • 1
  • 16
  • 25
0

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.

Community
  • 1
  • 1
OldCurmudgeon
  • 64,482
  • 16
  • 119
  • 213