HXSP1947
HXSP1947

Reputation: 1351

Java: Within abstract class create method that gets name of extending class

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.

Upvotes: 1

Views: 682

Answers (1)

Codebender
Codebender

Reputation: 14471

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.

Upvotes: 4

Related Questions