I have a class de.xyz.MyClass which is stored in de/xyz/MyClass.java How can I get this path inside the class MyClass ?
Like this:
String path = MyClass.class.getName().replace(".", "/") + ".java";
But note that sometimes class names are annotated (e.g., inner classes, etc.). More here.
If you're starting with an instance of the class (perhaps this inside one of the class's methods), you can get the class via instance.getClass(). For instance:
private String getPathToThis() {
return this.getClass().getName().replace(".", "/") + ".java";
}
Of course, these are going to be relative to some base (directory or jar) in the classpath...
I'm not sure if this answer you question so I'll do my best guess:
package de.xyz;
class PathForClass {
public static void main( String [] args ) {
System.out.println(
PathForClass.class.getResource( "PathForClass.class" )
);
}
}
Which when compiled and run gives:
C:\Users\Oscar\code>javac -d . PathForClass.java
C:\Users\Oscar\code>java -cp . de.xyz.PathForClass
file:/C:/Users/Oscar/code/de/xyz/PathForClass.class
That way you can modify a little the calls and have the path as you want:
package de.xyz;
class PathForClass {
public static void main( String [] args ) {
String currentDir = new java.io.File(".").toURI().toString();
String pathToClass = PathForClass.class.getResource( "PathForClass.class" ).toString();
System.out.println( pathToClass.substring( currentDir.length() - 2 )); // -2 to get rid of the /./ at the end of the current dir
}
}
C:\Users\Oscar\code>java -cp . de.xyz.PathForClass
de/xyz/PathForClass.class
Bear in mind that will only work where the classes are stored in directories, for jars you'll have to modify it a little bit ( if( pathToClass.startsWith("jar")){ //etc... )
Also, class loaders don't always work with the filesystem, some of them load files from databases, ldaps and pretty much anywhere, so is not always true that for de.xyz.MyClass there exists a de/xyz/MyClass.class file ( as shown with the jar example)
I hope you find this useful.