Yes. It works for all classes except classes loaded by bootstrap classloader. The other way to determine is:
Class klass = String.class;
URL location = klass.getResource('/'+klass.getName().replace('.', '/')+".class");
As notnoop pointed out getProtectionDomain().getCodeSource().getLocation()
method returns the location of the class file itself. For example:
jar:file:/jdk/jre/lib/rt.jar!/java/lang/String.class
file:/projects/classes/pkg/MyClass$1.class
The klass.getResource()
method returns the location of the jar file or CLASSPATH
file:/Users/home/java/libs/ejb3-persistence-1.0.2.GA.jar
file:/projects/classes