Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get caller class name from inherited static method

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)?

like image 801
Greg Witczak Avatar asked Sep 05 '13 23:09

Greg Witczak


1 Answers

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 :)

like image 88
Ben Brammer Avatar answered Sep 28 '22 13:09

Ben Brammer