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

隐身守侯 提交于 2020-01-25 14:30:13

问题


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.


回答1:


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"));



回答2:


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.




回答3:


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?



来源:https://stackoverflow.com/questions/26674037/possible-to-get-the-file-path-of-the-class-that-called-a-method-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!