在Java中转换为具体类和调用方法 [英] Cast to concrete class and call method in Java
问题描述
假设我们有一个名为 A
的基类和一些子类( B
, C
, D
等)。大多数子类都有方法 do()
,但是基础类没有。
类 AA
提供了一个名为 getObject()
的方法, $ c> B 或 C
或 D
如 A
。
Lets say we have a baseclass called A
and some subclasses (B
,C
,D
, etc.). Most subclasses have the method do()
but the baseclass does not.
Class AA
provides a method called getObject()
, which will create an object of type B
, or C
or D
, etc., but returns the object as type A
.
如何将返回的对象转换为具体类型并调用 do()
方法,如果此方法可用?
How do I cast the returned object to the concrete type and call its do()
method, if this method is available?
编辑:
改变类 A
的子类或 AA
的实现,因为im使用一个封闭的Source API。 。
I'm not allowed to change the implementation of Class A
, the subclasses or AA
, since im using a closed Source API.. And yeah, it does have some design issues, as you can see.
推荐答案
我认为一个更好的想法是实际上class A
定义 do()
方法作为抽象方法或具体的空方法。
I think a better idea is to actually have class A
define the do()
method either as an abstract method or as a concrete empty method. This way you won't have to do any cast.
如果您不允许更改任何类,那么您可以定义一个类 MyA扩展了定义
,...和 do()
方法和 MyB
的的
c> MyC MyAA
,这将基本上做 AA
,只是它返回类型 MyB
, MyC
...的对象
If you are not allowed to change any of the classes than you could define a class MyA extends A
which defines the do()
method and MyB
, MyC
,... and a MyAA
that would basically do what AA
does, just that it returns objects of type MyB
, MyC
....
如果这不是确定的,那么我没有看到另一种方法检查返回的对象是否类型 B
,并转换为 B
等。
If this is not ok then I don't see another way than checking if the returned object is of type B
and do a cast to B
and so on.
这篇关于在Java中转换为具体类和调用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!