[英]How to return object class without creating new one?
I have hierarchy of few classes: Organism -> Fox,Antelope,Wolf我有几个类的层次结构:有机体-> Fox,Antelope,Wolf
And i want to create a method that will define what is the class of the given object, without returning new instance of this object.我想创建一个方法来定义给定 object 的 class 是什么,而不返回这个 object 的新实例。
Something like this:像这样的东西:
public Organism defineOrganismClass(Organism o) {
if (o instanceof Antelope) {
return ...;
}if (o instanceof Fox) {
return ...;
} //and so on
}
Is there a way to do it?有没有办法做到这一点?
Yes, you can return Class<? extends Organism>
是的,您可以返回
Class<? extends Organism>
Class<? extends Organism>
instead, eg Fox.class
.改为
Class<? extends Organism>
,例如Fox.class
。 This will give you the class definition, but no instance.这将为您提供 class 定义,但没有实例。 You would not need the
if
statements, just return o.getClass()
.您不需要
if
语句,只需return o.getClass()
。
It does of course beg the question what you then want to do with that class.它当然会提出一个问题,然后你想用那个 class 做什么。 Maybe you want to define an enum instead, eg
enum OrganismType { ANTELOPE, FOX }
which is easier to operate on.也许你想定义一个枚举,例如
enum OrganismType { ANTELOPE, FOX }
,它更容易操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.