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?
在Java中,在抽象类中,我可以获得扩展它的具体类的实例吗?
If so, can I see a code example?
如果是这样,我能看到代码示例吗?
1 个解决方案
#1
67
Yes, you can do this by calling this.getClass()
. This will give you the Class
instance for the runtime type of this
.
是的,您可以通过调用this.getClass()来完成此操作。这将为您提供此运行时类型的Class实例。
If you just want the name of the class, you could use this.getClass().getName()
.
如果您只想要类的名称,可以使用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.
最后,还有this.getClass()。getSimpleName()和this.getClass()。getCanonicalName()。我一直使用前者将可读类名打印到日志文件等。
#1
67
Yes, you can do this by calling this.getClass()
. This will give you the Class
instance for the runtime type of this
.
是的,您可以通过调用this.getClass()来完成此操作。这将为您提供此运行时类型的Class实例。
If you just want the name of the class, you could use this.getClass().getName()
.
如果您只想要类的名称,可以使用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.
最后,还有this.getClass()。getSimpleName()和this.getClass()。getCanonicalName()。我一直使用前者将可读类名打印到日志文件等。