I have a class de.xyz.MyClass
which is stored in de/xyz/MyClass.java
.
How can I get this path from the class MyClass
itself?
Basically there is no difference, both are the same. In both the cases, the folder structure will be src/com/utils . Show activity on this post. "Packaging helps us to avoid class name collision when we use the same class name as that of others.
CLASSPATH is an environment variable (i.e., global variables of the operating system available to all the processes) needed for the Java compiler and runtime to locate the Java packages/classes used in a Java program.
The compiler relies on the names of source files to find and compile dependent classes.
lang. * and java. util. *, these live in the "lib" directory under wherever your Java Runtime Environment (JRE) is installed.
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With