英文:
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 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 -> {}
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论