Reputation: 1684
I have following classes (note that methods are static):
class Base
{
public static void whosYourDaddy()
{
Class callerClass = // what should I write here to get caller class?
System.out.print(callerClass.getName());
}
}
Class A extends Base
{
public static void foo()
{
A.whosYourDaddy();
}
}
Class B extends Base
{
public static void bar()
{
B.whosYourDaddy();
}
}
And when I call:
A.foo();
B.bar();
I'd like to get output:
AB
instead of BaseBase
. Is it even possible with static methods (in Java 7)?
Upvotes: 8
Views: 6892
Reputation: 1
private static class Reflection { private static final SecurityManager INSTANCE = new SecurityManager(); static Class getCallClass() { return INSTANCE.getCallClass(2); } private Reflection() { } private static class SecurityManager extends java.lang.SecurityManager { public Class getCallClass(int i) { Class[] classContext = getClassContext(); if (i >= 0 && i + 1 < classContext.length) { return classContext[i + 1]; } return null; } }; }
Upvotes: 0
Reputation: 998
What you can do, but shouldn't :) is use the Throwable getStackTrace method. Aside from the smell, this is pretty slow, because getting the stack trace isn't that fast. But you will get an array of StackTraceElement, and each one will contain the class of teh class that is calling it (and you can also get the file and line, and if you separate the two with a : you can get a clickable link in eclipse, not that I'd ever do such a thing...).
Something like
String className = new Throwable().getStackTrace()[1].getClassName();
Hope that helps :)
Upvotes: 8
Reputation: 4425
Is it even possible with static methods (in Java 7)?
No, Static methods aren't inherited. Only non-static methods are inherited.
In your case change Base
(and subclasses) as follows:
class Base
{
public void whosYourDaddy()
{
Class<?> callerClass = getClass();
System.out.print(callerClass.getName());
}
}
Upvotes: -1