Java类的elegant向下转型

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

elegant Java class downcast

问题

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

  1. public void handleStuff(A someObject) {
  2. if(someObject instanceof AB){
  3. ((AB)someObject).someABFunction();
  4. } else if(someObject instanceof AC) {
  5. ((AC)someObject).someACFunction();
  6. }
  7. }
  8. 我不喜欢这里的双重检查/转换操作有没有其他方法编写代码而不是先检查类型然后再转换我知道可以使用两个重载的函数ABAC作为参数但我想要的是更少的代码而不是更多 :-) 类似这样的东西
  9. ```java
  10. public void handleStuff(A someObject) {
  11. if(someObject instanceof AB){
  12. someObject.someABFunction(); // 已经明确知道这是AB
  13. } else if(someObject instanceof AC) {
  14. someObject.someACFunction(); // 已经明确知道这是AC
  15. }
  16. }
英文:

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

  1. public void handleStuff(A someObject) {
  2. if(someObject instanceof AB){
  3. ((AB)someObject).someABFunction();
  4. } else if(someObject instanceof AC) {
  5. ((AC)someObject).someACFunction();
  6. }
  7. }

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:

  1. public void handleStuff(A someObject) {
  2. if(someObject instanceof AB){
  3. someObject.someABFunction(); // it is already clear that this is AB
  4. } else if(someObject instanceof AC) {
  5. someObject.someACFunction(); // it is already clear that this is AC
  6. }
  7. }

答案1

得分: 7

  1. Java 16及更高版本中,您可以使用模式匹配来避免强制转换。像这样:
  2. public void handleStuff(A someObject) {
  3. if (someObject instanceof AB ab) {
  4. ab.someABFunction();
  5. } else if (someObject instanceof AC ac) {
  6. ac.someACFunction();
  7. }
  8. }
  9. Java 17及更高版本中,您可以启用switch表达式的模式匹配预览特性,以进一步缩短代码。有了这个特性,您可以这样做:
  10. public void handleStuff(A someObject) {
  11. switch (someObject) {
  12. case AB ab -> ab.someABFunction();
  13. case AC ac -> ac.someACFunction();
  14. default -> {}
  15. }
  16. }
英文:

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

  1. public void handleStuff(A someObject) {
  2. if (someObject instanceof AB ab) {
  3. ab.someABFunction();
  4. } else if (someObject instanceof AC ac) {
  5. ac.someACFunction();
  6. }
  7. }

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:

  1. public void handleStuff(A someObject) {
  2. switch (someObject) {
  3. case AB ab -> ab.someABFunction();
  4. case AC ac -> ac.someACFunction();
  5. default -> {}
  6. }
  7. }

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:

确定