将变量声明为某种类型

Joh*_*Eye 7 java casting type-conversion

假设我们有以下代码块:

if (thing instanceof ObjectType) {
    ((ObjectType)thing).operation1();
    ((ObjectType)thing).operation2();
    ((ObjectType)thing).operation3();
}
Run Code Online (Sandbox Code Playgroud)

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

OjectType differentThing = (ObjectType)thing;
Run Code Online (Sandbox Code Playgroud)

从那时起开始使用'differentThing',但这会给代码带来一些困惑.有没有更好的方法来做到这一点,可能是这样的

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

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

Jon*_*eet 9

不,一旦声明了变量,该变量的类型就是固定的.我认为,改变变量的类型(可能是暂时的)会带来远远更多的混乱比:

ObjectType differentThing = (ObjectType)thing;
Run Code Online (Sandbox Code Playgroud)

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

另一种选择是提取方法:

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

private void performOperations(ObjectType thing) {
    thing.operation1();
    thing.operation2();
    thing.operation3();
}
Run Code Online (Sandbox Code Playgroud)