如何检测在Java 8中会导致ClassCastException的模糊方法调用? [英] How to detect ambiguous method calls that would cause a ClassCastException in Java 8?
问题描述
public class Test {
public static void main(String [] args){
System.out.println (将String.valueOf(GETVAL( XXX))); // 7:打印结果8:例外
}
@SuppressWarnings(未选中)
public static< T> T getVal(T param){
//根据参数做一些计算...
return param; //实际返回类型只依赖于param,因此调用者知道期望什么
code $ $ $ $ $ $ $ $ $ $ $ $ b 可以在Java 7和Java 8中使用。
We are currently in the process of migrating an application from Java 7 to Java 8. After fixing a some compilation issues, I stumbled upon an issue similar to the following question: ClassCast Error: Java 7 vs Java 8.
To summarise, here is a sample code that shows the issue:
public class Test {
public static void main(String[] args) {
System.out.println(String.valueOf(getVal("xxx"))); // 7: prints the result, 8: Exception
}
@SuppressWarnings("unchecked")
public static <T> T getVal(String param) {
// do some computation based on param...
return (T) result; // actual return type only depends on param so the caller knows what to expect
}
}
The idea was that we would thrust that the caller knows the expected type, and this would avoid him an explicit cast (I don't say this was a good idea…). In a lot of cases, the caller just expects an Object
so there was no implicit cast at all.
As stated in the question above, the String.valueOf
example worked fine in Java 7 because there was no type inference, hence Object
was assumed. Now in Java 8, the compiler chooses the most specific type (here char[]
), which causes a ClastCastException
at runtime.
The problem is that we have around 350 calls of this getVal
method. Is there a way to detect overloaded method calls that would differ between Java 7 and Java 8? I.E. detect when the Java 8 compiler would select a different method from the Java 7 compiler.
解决方案 A better alternative would be:
public class Test {
public static void main(String[] args) {
System.out.println(String.valueOf(getVal("xxx"))); // 7: prints the result, 8: Exception
}
@SuppressWarnings("unchecked")
public static <T> T getVal(T param) {
// do some computation based on param...
return param; // actual return type only depends on param so the caller knows what to expect
}
}
which will work in both Java 7 and Java 8.
这篇关于如何检测在Java 8中会导致ClassCastException的模糊方法调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!