简体   繁体   English

Java获取这个的运行时类?

[英]Java get runtime class of this?

Say I have the following object hierarchy: 说我有以下对象层次结构:

public abstract class Animal {
    ...
}

public class Canine extends Animal {
    ...
}

public class Feline extends Animal {
    ...
}

public class Dog extends Canine {
    ...
}

public class Wolf extends Canine {
    ...
}

public class Leopard extends Feline {
    ...
}

Let's say the Animal class has a final method that needs to take different actions depending on what the object's runtime type/class is: 假设Animal类具有一个final方法,该方法需要根据对象的运行时类型/类采取不同的操作:

public abstract class Animal {
    // Lots of stuff blah blah blah

    public final makeNoise() {
        // If we're a Dog, then System.out.println("Woof!");
        // Else if we're a Wolf, then System.out.println("Gggrrrrr!");
        // etc.
    }
}

Here's the kicker: I know that best practices and OOP would have me write makeNoise() to be an abstract method, and then just implement a different version in each subclass. 这是一个关键:知道最佳实践和OOP会让我编写makeNoise()作为抽象方法,然后在每个子类中实现一个不同的版本。 However , for reasons outside the scope of this question, I can't do that. 但是 ,由于超出此问题范围的原因,我无法做到这一点。

So, barring best OOP practices, how can I tell - from inside the parent makeNoise() method - what our runtime class is? 因此,除非有最佳的OOP惯例, makeNoise()如何从父makeNoise()方法内部makeNoise()我们的运行时类是什么?

You could use the instanceof operator: What is the 'instanceof' operator used for? 您可以使用instanceof运算符: “ instanceof”运算符用于什么?

Bear in mind that doing things the way you're asking will require Animal to know about all of its subclasses (direct and otherwise). 请记住,按照您的要求做事将要求Animal知道其所有子类(直接和其他)。 This clearly does not scale and invites maintenance problems. 显然,这无法扩展,并且会引起维护问题。

To get the runtime class use getClass(). 要获取运行时类,请使用getClass()。 It will return the sub-class even though the code is in the super-class. 即使代码在超类中,它也将返回子类。

this.getClass()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM