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

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

例如:

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

现在,如果方法返回A的对象,我可以找出它是B型还是C

使用instanceofClass#getClass()

 A returned = getA(); if (returned instanceof B) { .. } else if (returned instanceof C) { .. } 

getClass()将返回: A.classB.classC.class

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

 ((B) returned).doSomethingSpecificToB(); 

也就是说,有时候认为使用instanceofgetClass()是一种不好的做法。 你应该使用多态来试图避免检查具体的子类,但我不能告诉你更多的信息。

你尝试过使用instanceof吗?

例如

 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 ,或者调用它的getClass()方法。

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

正如这里所回答的,您可以使用这种非常简单的方法。

 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 

无需存储其他Strings ,检查instanceofoverride任何子类中的方法。

有两种方法我可以想到1)一种使用JavareflectionAPI 2)其他一种方法可以使用instanceOf

其他方法可以是比较对象,我不知道它是怎么回事,你可以试试这个

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

 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 = new A(); a.getClassname(); // returns "A" B b = new B(); b.getClassname(); // returns "B" ((A)b).getClassname(); // Also returns "B" 

因为它被转换为“A”对象,它将调用“A” getClassname()函数,但将返回由构造函数设置的值,该构造函数是“B”构造函数。

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