Get Concrete Class name from Abstract Class

2019-01-23 22:12发布

问题:

I apologize if this question has been asked already. I searched the questions and could not find an answer.

In Java, inside an abstract class can I get the instance of the concrete class that extends it?

If so, can I see a code example?

回答1:

Yes, you can do this by calling this.getClass(). This will give you the Class instance for the runtime type of this.

If you just want the name of the class, you could use this.getClass().getName().

Lastly, there are also this.getClass().getSimpleName() and this.getClass().getCanonicalName(). I use the former all the time to print readable class names to log files and the like.