可以获取在Java中调用方法的类的文件路径吗? [英] Possible to get the file-path of the class that called a method in Java?
问题描述
比方说我有这个场景
C:\ Users \ Name \ Document \ Workspace \ Project \ Src\Com\Name\Foo.java
C:\Users\Name\Documents\Workspace\Project\Src\Com\Name\Foo.java
Public class Foo {
public Foo() {
Bar b = new Bar();
b.method();
}
}
然后我们可以说课程栏位于.JAR中正在用作库的文件,是否可以确定调用method()的类来自何处? (在这种情况下,Foo类)
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.
推荐答案
如果你需要从方法Bar#方法中获取调用者类文件的路径,那么你可以使用这样的东西:
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"));
这篇关于可以获取在Java中调用方法的类的文件路径吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!