Java 将变量声明为特定类型
假设我们有以下代码块:Java 将变量声明为特定类型,java,casting,type-conversion,Java,Casting,Type Conversion,假设我们有以下代码块: if (thing instanceof ObjectType) { ((ObjectType)thing).operation1(); ((ObjectType)thing).operation2(); ((ObjectType)thing).operation3(); } 所有的类型转换都让代码看起来很难看,有没有一种方法可以在代码块中将“thing”声明为ObjectType?我知道我能做到 OjectType differentThing
if (thing instanceof ObjectType) {
((ObjectType)thing).operation1();
((ObjectType)thing).operation2();
((ObjectType)thing).operation3();
}
所有的类型转换都让代码看起来很难看,有没有一种方法可以在代码块中将“thing”声明为ObjectType?我知道我能做到
OjectType differentThing = (ObjectType)thing;
并且从那时起使用“Differenting”,但这会给代码带来一些混乱。有没有更好的方法,比如
if (thing instanceof ObjectType) {
(ObjectType)thing; //this would declare 'thing' to be an instance of ObjectType
thing.operation1();
thing.operation2();
thing.operation3();
}
我很确定这个问题以前有人问过,但我找不到。请随意指出可能的重复项。否,一旦声明了变量,该变量的类型就固定了。我相信改变变量的类型(可能是暂时的)会带来比以下更大的混乱:
ObjectType differentThing = (ObjectType)thing;
你认为这种方法令人困惑。这种方法被广泛使用和惯用——当然,这是必须的。(这通常有点代码味道。)
另一个选项是提取方法:
if (thing instanceof ObjectType) {
performOperations((ObjectType) thing);
}
...
private void performOperations(ObjectType thing) {
thing.operation1();
thing.operation2();
thing.operation3();
}
变量一旦声明,其类型就不能更改。您的
差异化方法是正确的:
if (thing instanceof ObjectType) {
OjectType differentThing = (ObjectType)thing;
differentThing.operation1();
differentThing.operation2();
differentThing.operation3();
}
我也不会说它令人困惑:只要differenting
变量的范围限于if
操作符的主体,读者就可以清楚地知道发生了什么。遗憾的是,这是不可能的
原因是这个作用域中的“东西”将始终是相同的对象类型,并且您不能在一个代码块中重铸它
如果您不喜欢有两个变量名(比如thing和castedThing),您可以创建另一个函数
if (thing instanceof ObjectType) {
processObjectType((ObjectType)thing);
}
..
private void processObjectType(ObjectType thing) {
thing.operation1();
thing.operation2();
thing.operation3();
}
我认为除了你提到的方式之外,没有其他方式了。