【发布时间】:2012-06-26 13:25:24
【问题描述】:
假设我们有以下代码块:
if (thing instanceof ObjectType) {
((ObjectType)thing).operation1();
((ObjectType)thing).operation2();
((ObjectType)thing).operation3();
}
所有的类型转换使代码看起来很难看,有没有办法在代码块中将“事物”声明为 ObjectType?我知道我能做到
OjectType differentThing = (ObjectType)thing;
并从那时起使用“不同的东西”,但这会给代码带来一些混乱。有没有更好的方法来做到这一点,可能像
if (thing instanceof ObjectType) {
(ObjectType)thing; //this would declare 'thing' to be an instance of ObjectType
thing.operation1();
thing.operation2();
thing.operation3();
}
我很确定以前有人问过这个问题,但我找不到。请随意指出可能的重复项。
【问题讨论】:
-
我认为除了您提到的方式之外没有其他方式。
标签: java casting type-conversion