Vai*_*esh 15 java oop reflection inheritance
有没有办法从基类实例中找出派生类的名称?
例如:
class A{
....
}
class B extends A{
...
}
class c extends A{
...
}
Run Code Online (Sandbox Code Playgroud)
现在如果一个方法返回一个对象A,我可以找出它是否是类型B或C?
Boz*_*zho 19
使用instanceof或者Class#getClass()
A returned = getA();
if (returned instanceof B) { .. }
else if (returned instanceof C) { .. }
Run Code Online (Sandbox Code Playgroud)
getClass()将返回之一:A.class,B.class,C.class
在if子句中你需要向下转换 - 即
((B) returned).doSomethingSpecificToB();
Run Code Online (Sandbox Code Playgroud)
也就是说,有时它被认为是使用instanceof或是getClass()一种不好的做法.你应该使用多态来试图避免检查具体的子类,但我不能告诉你更多的信息.
您是否尝试过使用 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.
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
35024 次 |
| 最近记录: |