Java类的elegant向下转型

huangapple go评论67阅读模式
英文:

elegant Java class downcast

问题

让A是AB和AC的超类。给定一个方法:

public void handleStuff(A someObject) {
  if(someObject instanceof AB){ 
     ((AB)someObject).someABFunction();
  } else if(someObject instanceof AC) {
     ((AC)someObject).someACFunction();
  }
}
我不喜欢这里的双重检查/转换操作有没有其他方法编写代码而不是先检查类型然后再转换我知道可以使用两个重载的函数将AB或AC作为参数但我想要的是更少的代码而不是更多 :-) 类似这样的东西

```java
public void handleStuff(A someObject) {
  if(someObject instanceof AB){ 
     someObject.someABFunction(); // 已经明确知道这是AB
  } else if(someObject instanceof AC) {
     someObject.someACFunction(); // 已经明确知道这是AC
  }
}
英文:

Let A be a superclass of AB and AC. Given a method:

public void handleStuff(A someObject) {
  if(someObject instanceof AB){ 
     ((AB)someObject).someABFunction();
  } else if(someObject instanceof AC) {
     ((AC)someObject).someACFunction();
  }
}

I don't like the double checking/casting operation here; is there any other way to code this without first checking for a type and then casting? I know I could do it with two overloaded functions that take AB or AC as parameters, but I was looking for less code, not more Java类的elegant向下转型 Something like:

public void handleStuff(A someObject) {
  if(someObject instanceof AB){ 
     someObject.someABFunction(); // it is already clear that this is AB
  } else if(someObject instanceof AC) {
     someObject.someACFunction(); // it is already clear that this is AC
  }
}

答案1

得分: 7

在Java 16及更高版本中,您可以使用模式匹配来避免强制转换。像这样:

    public void handleStuff(A someObject) {
      if (someObject instanceof AB ab) { 
         ab.someABFunction();
      } else if (someObject instanceof AC ac) {
         ac.someACFunction();
      }
    }

在Java 17及更高版本中,您可以启用switch表达式的模式匹配预览特性,以进一步缩短代码。有了这个特性,您可以这样做:

    public void handleStuff(A someObject) {
      switch (someObject) {
        case AB ab -> ab.someABFunction();
        case AC ac -> ac.someACFunction();
        default -> {}
      }
    }
英文:

On Java 16 and newer, you can use pattern matching to avoid the cast. Like this:

public void handleStuff(A someObject) {
  if (someObject instanceof AB ab) { 
     ab.someABFunction();
  } else if (someObject instanceof AC ac) {
     ac.someACFunction();
  }
}

On Java 17 and newer, you can enable the preview feature for pattern matching in switch-expressions to shorten it further. With that feature, you can do this:

public void handleStuff(A someObject) {
  switch (someObject) {
    case AB ab -> ab.someABFunction();
    case AC ac -> ac.someACFunction();
    default -> {}
  }
}

huangapple
  • 本文由 发表于 2023年4月4日 17:30:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/75927745.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定