如何从基类实例中找出子类?

问题描述 投票:15回答:6

有没有办法从基类实例中找出派生类的名称?

e.f.:

class A{
    ....
}
class B extends A{
    ...
}
class c extends A{
    ...
}

现在,如果一个方法返回A的一个对象,我能否知道它是qzexswpoi还是B

java oop reflection inheritance
6个回答
19
投票

使用Cinstanceof

Class#getClass()

A returned = getA(); if (returned instanceof B) { .. } else if (returned instanceof C) { .. } 将返回以下任何一个:getClass()A.classB.class

在if子句中你需要向下转换 - 即

C.class

也就是说,有时候认为使用((B) returned).doSomethingSpecificToB(); instanceof是一种不好的做法。您应该使用getClass()来避免检查具体的子类,但我不能告诉您更多信息。


4
投票

你尝试过使用polymorphism吗?

EG

instanceof

2
投票

简短回答你的问题

有没有办法从基类对象中找出派生类的名称?

不,超类无法告诉子类的名称/类型。

你必须询问对象(这是一个子类的实例)并询问它是否是:Class A aDerived= something.getSomethingDerivedFromClassA(); if (aDerived instanceof B) { } else if (aDerived instanceof C) { } //Use type-casting where necessary in the if-then statement. 一个特定的子类,或者称它为instanceof方法。


1
投票

有没有办法从基类实例中找出派生类的名称?

正如getClass()所说,你可以使用这种非常简单的方法。

here

然后只需打印当前的abstract class A { public final String getName() { return this.getClass().getName(); } } class B extends A { } class C extends A { } 名称:

class

输出:

B b = new B();
C c = new C();

System.out.println(b.getName());
System.out.println(c.getName());

没有必要存储额外的com.test.B com.test.C ,检查Stringsinstanceof方法在任何子类中。


0
投票

有两种方法我可以想到1)一种使用Java反射API 2)另一种方法是使用instanceOf

其他方法可以是比较对象的对象,我不知道它可能是什么,你可以试试这个


0
投票

您可以在子类的构造函数中执行此操作

override

所以

class A {
    protected String classname;
    public A() { this.classname = "A"; }
    public String getClassname() { return this.classname; }
}
class B extends A {
    public B() {
        super();
        this.classname = "B";
    }
}

因为它被转换为“A”对象,它将调用“A”A a = new A(); a.getClassname(); // returns "A" B b = new B(); b.getClassname(); // returns "B" ((A)b).getClassname(); // Also returns "B" 函数,但将返回由构造函数设置的值,该构造函数是“B”构造函数。

注意:在设置之前调用getClassname()

© www.soinside.com 2019 - 2024. All rights reserved.