【问题标题】:Declaring variable to be of certain type将变量声明为某种类型
【发布时间】: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


【解决方案1】:

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

ObjectType differentThing = (ObjectType)thing;

您认为令人困惑的方法。这种方法被广泛使用和惯用 - 当然,在所有需要它的地方。 (这通常有点代码味道。)

另一种选择是提取方法:

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

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

【讨论】:

    【解决方案2】:

    变量一旦被声明,它的类型就不能改变。您的differentThing 方法是正确的:

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

    我也不认为它令人困惑:只要 differentThing 变量的范围仅限于 if 运算符的主体,读者就很清楚发生了什么。

    【讨论】:

      【解决方案3】:

      很遗憾,这是不可能的。

      原因是这个作用域中的“事物”将始终属于相同的对象类型,并且您不能在代码块中对其进行重铸。

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

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

      【讨论】:

        猜你喜欢
        • 2020-07-13
        • 2010-12-22
        • 2016-07-03
        • 1970-01-01
        • 2012-07-23
        • 1970-01-01
        • 1970-01-01
        • 2018-12-16
        • 1970-01-01
        相关资源
        最近更新 更多