简体   繁体   中英

Possible to get the file-path of the class that called a method in Java?

Let's say for instance I have this scenario

C:\\Users\\Name\\Documents\\Workspace\\Project\\Src\\Com\\Name\\Foo.java

Public class Foo {

    public Foo() {
        Bar b = new Bar();
        b.method();
    }
}

Then lets say that class Bar is in a .JAR file that's being used as a library, is it possible to figure out where the class that called method() was from? (in this case, the Foo class)

I've done a little looking around Google and can't find anything, and this code would definately simplify my library quite a bit.

If you need to get path of the caller class file from inside the method Bar#method then you can use something like this:

StackTraceElement[] stackTrace = new Throwable().getStackTrace();
String callerFilePath = getClass().getClassLoader().getResource(stackTrace[1].getClassName().replace('.', '/') + ".class"));

Yes, you can get the path from where the file is being executed. For example, you have the file : C:\\Users\\Name\\Documents\\Workspace\\Project\\Src\\Com\\Name\\Foo.java

After compiling, it will change to : C:\\Users\\Name\\Documents\\Workspace\\Project\\Src\\Com\\Name\\Foo.class

You can use this to get the directory of the file:

System.getProperty("user.dir");

and then you can add this String to it:

String cPath = System.getProperty("user.dir")+"\\Foo.class";

Thus, cPath would be the complete path to the file.

You can use Foo.class.getResource("Foo.class") to get the location of the compiled class file. The question is, how will this help you simplify your library?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM