0

Thanks in advance for the help.

First off, I don't think what I want to do is possible, but I thought I might ask anyway. I have an abstract class foo with a method bar. I have several classes that extend this class and none override the method bar (though all frequently call bar). I am trying to debug an issue and would like to print out the name of the class that calls bar. So if a class temp extends foo and calls bar, "temp" will be printed out.

One approach would be to override the bar method for every class that extends foo, but this would be a bit of a pain since it also instantiates private variables in foo. I would therefore need separate methods to instantiate each variable that is private in foo to override bar in temp.

What I would like to do is something like this

System.out.println(Class.getSimpleName());

but I can't do this because getSimpleName() is not a static method and therefore can be called within something that can't be instantiated. Another approach would be to make foo a normal class (ie not abstract). However, I would really prefer not to do this.

Is there anyway that I can do what I would like to do or am I going to have to "bite the proverbial bullet"?

Edit: This code is part of an android application.

HXSP1947
  • 1,311
  • 1
  • 16
  • 39
  • Would [this](http://stackoverflow.com/questions/5077770/java-printing-current-backtrace) help? You would basically stick that in your `foo` method within the abstract class. – npinti Aug 25 '15 at 07:48
  • 3
    Are you looking for something like `this.getClass().getSimpleName()`. This will only print the class name of the object (of a subclass), not Foo itself. – Codebender Aug 25 '15 at 07:51
  • No it won't. I should have specified that I am using this java class in an android application. I have editing my question to reflect this – HXSP1947 Aug 25 '15 at 07:51
  • @Codebender worked like a charm. If you want to add an answer I will accept it. Why might this have worked over Class.getSimpleName()? – HXSP1947 Aug 25 '15 at 07:55
  • 1
    Because `getSimpleName` is not a static method. You need a *specific `Class` instance* for it to work. – RealSkeptic Aug 25 '15 at 07:57
  • @user2736423 it works because this.getClass() returns the class object – hermit Aug 25 '15 at 07:58

1 Answers1

4

You could just do something like,

this.getClass().getSimpleName();

This will only print the class name of the object (of a subclass), not Foo itself.

It work's because this refers to the object (which belongs to a concrete subclass) and NOT the class itself (Foo in this case) it's being used in.

Codebender
  • 14,221
  • 7
  • 48
  • 85