Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert package name to path

Tags:

java

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?

like image 953
rocksportrocker Avatar asked Dec 17 '09 13:12

rocksportrocker


People also ask

Is a package just a folder Java?

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.

What is classpath in packages in Java?

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.

How does compiler locate packages in Java?

The compiler relies on the names of source files to find and compile dependent classes.

Where is Java Lang package located?

lang. * and java. util. *, these live in the "lib" directory under wherever your Java Runtime Environment (JRE) is installed.


1 Answers

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...

like image 72
T.J. Crowder Avatar answered Sep 21 '22 09:09

T.J. Crowder