0

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.

Hobbyist
  • 15,888
  • 9
  • 46
  • 98

3 Answers3

3

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"));
alexmagnus
  • 976
  • 5
  • 7
0

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.

dryairship
  • 6,022
  • 4
  • 28
  • 54
  • This is not doing what I'm asking, sorry if I wasn't clear, I want to get the class that called the method, So if Jake.class calls a method in Jim.class, I want to return to path of Jake.class – Hobbyist Oct 31 '14 at 19:13
0

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?

jmn
  • 564
  • 5
  • 8