简体   繁体   English

如何在不创建新的情况下返回 object class?

[英]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.

相关问题 如何在不创建新对象的情况下更改对象的类? - How to change the class of an object without creating a new one? 如何在不创建新对象的情况下从另一个类访问变量 - How to Access Variable from Another Class without Creating New Object 如何在不创建新字体对象的情况下更改字体对象? - How to change a font object without creating a new one? 如何在不创建新类或修改类的情况下将新字段/数据“附加”到对象中? - How to “append” new field/data into an object without creating a new class nor modifying the class? 如何在不使用&#39;+&#39;或任何内置函数的情况下在&#39;String&#39;类中创建新对象的情况下在1个对象中并置两个字符串 - How to concat two strings in 1 object without creating new object in 'String' class without using '+' or any inbuilt function How can I copy existing class object to other class new class object without creating copy of original object(in memory) in Java - How can I copy existing class object to other class new class object without creating copy of original object(in memory) in Java 如何在不创建新位图的情况下旋转位图? - How to rotate Bitmap without creating a new one? 如何使类不允许创建新对象(new Object()) - how to make class to not allow creating new object (new Object()) 如何在不创建新对象的情况下从另一个类访问非静态变量 - How to Access non static variable from Another Class without Creating New Object 如何返回一个常量值,而不是每次都创建一个新的 object - How to return a constant value, not creating a new object every time
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM