如果类B和类C扩展了类A,我有一个类型为B或C的对象,我如何确定它是哪种类型的实例?


当前回答

我在我的GeneralUtils类中使用blow函数,检查它可能有用

    public String getFieldType(Object o) {
    if (o == null) {
        return "Unable to identify the class name";
    }
    return o.getClass().getName();
}

其他回答

任何建议的方法的使用都被认为是基于糟糕的OO设计的代码气味。

如果您的设计很好,您应该不会发现自己需要使用getClass()或instanceof。

任何建议的方法都可以,但只是在设计方面要记住一些东西。

我在我的GeneralUtils类中使用blow函数,检查它可能有用

    public String getFieldType(Object o) {
    if (o == null) {
        return "Unable to identify the class name";
    }
    return o.getClass().getName();
}

如果你想在运行时知道,用isinstance()检查是不够的。 使用:

if(someObject.getClass().equals(C.class){
    // do something
}

您可以使用getSimpleName()。

假设我们有一个对象:Dog d = new Dog(),

我们可以使用下面的语句来获取类名:Dog。例如:

.getSimpleName d.getClass () ();//返回String 'Dog'。

PS: d.g getclass()会给你对象的全名。

if (obj instanceof C) {
//your code
}