将变量声明为某种类型

时间:2012-06-25 09:38:15

标签: java casting type-conversion

假设我们有以下代码块:

if (thing instanceof ObjectType) {
    ((ObjectType)thing).operation1();
    ((ObjectType)thing).operation2();
    ((ObjectType)thing).operation3();
}

所有类型转换使得代码看起来很难看,有没有办法在该代码块中将'thing'声明为ObjectType?我知道我能做到

OjectType differentThing = (ObjectType)thing;

从此开始使用'differentThing',但这会给代码带来一些困惑。有没有更好的方法来做到这一点,可能像

if (thing instanceof ObjectType) {
    (ObjectType)thing; //this would declare 'thing' to be an instance of ObjectType
    thing.operation1();
    thing.operation2();
    thing.operation3();
}

我很确定过去曾问过这个问题,但我找不到它。请随意指出可能的副本。

3 个答案:

答案 0 :(得分:9)

不,一旦声明了变量,该变量的类型就是固定的。我认为改变变量的类型(可能是暂时的)会使比以下更加混乱:

ObjectType differentThing = (ObjectType)thing;

接近你认为是混乱。这种方法被广泛使用和惯用 - 当然,它是必需的。 (这通常有点代码味道。)

另一种选择是提取方法:

if (thing instanceof ObjectType) {
    performOperations((ObjectType) thing);
}
...

private void performOperations(ObjectType thing) {
    thing.operation1();
    thing.operation2();
    thing.operation3();
}

答案 1 :(得分:4)

声明变量后,其类型无法更改。您的differentThing方法是正确的:

if (thing instanceof ObjectType) {
    OjectType differentThing = (ObjectType)thing;
    differentThing.operation1();
    differentThing.operation2();
    differentThing.operation3();
}

我也不会把它称为混淆:只要differentThing变量的范围仅限于if运算符的主体,读者就会明白发生了什么

答案 2 :(得分:2)

可悲的是,这是不可能的。

原因是此范围中的“thing”将始终具有相同的对象类型,并且您无法在代码块中重新创建它。

如果你不喜欢有两个变量名(比如thing和castedThing),你总是可以创建另一个函数;

if (thing instanceof ObjectType) {
    processObjectType((ObjectType)thing);
}
..

private void processObjectType(ObjectType thing) {
    thing.operation1();
    thing.operation2();
    thing.operation3();
}
相关问题