说我有一个基类:铸造基地型与Java
abstract class TheBase {}
class Foo extends TheBase {}
class Bar extends TheBase {}
我想“投”基对象插入此类型:
TheBase obj = getFromSomewhere();
Foo foo = obj.asA(Foo.class);
Bar bar = obj.asA(Bar.class);
asA
将抛出一个例外,我有定义为:CustomCannotCastException()
这可能吗?
起初,不要在TheBase类中进行强制转换。让来电者决定,你得到的是哪个类 –
@JordiLaforge:但是调用者正在决定她想要哪个类(通过参数)。 – Thilo
为什么重新发明标准的铸造机制?为什么不做'Foo foo =(Foo)obj;'?为什么你自己的'CustomCannotCastException'而不是使用标准的'ClassCastException'? – Jesper