简体   繁体   English

可以获取在Java中调用方法的类的文件路径吗?

[英]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 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? 然后,假设Bar类位于用作库的.JAR文件中,是否可以找出调用method()的类的来源? (in this case, the Foo class) (在这种情况下,是Foo类)

I've done a little looking around Google and can't find anything, and this code would definately simplify my library quite a bit. 我已经在Google周围四处寻找了东西,但找不到任何东西,这段代码一定会简化我的图书馆。

If you need to get path of the caller class file from inside the method Bar#method then you can use something like this: 如果您需要从方法Bar#method中获取调用者类文件的路径,则可以使用以下方法:

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 例如,您有以下文件: 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 编译后,它将更改为: 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. 因此, cPath将是文件的完整路径。

You can use Foo.class.getResource("Foo.class") to get the location of the compiled class file. 您可以使用Foo.class.getResource("Foo.class")来获取已编译的类文件的位置。 The question is, how will this help you simplify your library? 问题是,这将如何帮助您简化库?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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