How to detect ambiguous method calls that would cause a ClassCastException in Java 8?

前端 未结 2 1946
野性不改
野性不改 2021-02-20 09:49

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 ques

相关标签:
2条回答
  • 2021-02-20 10:04

    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.

    0 讨论(0)
  • 2021-02-20 10:22

    In the end the solution was to change getVal() to return Object:

        public static Object getVal(String param) {
            // do some computation based on param...
            return result;
        }
    

    and add a second method that also takes the desired class as parameter:

        public static <T> T getVal(String param, Class<T> clazz) {
            return clazz.cast(getVal(param));
        }
    

    then fix all compilation issues (where caller didn't expect Object) by adding the appropriate class parameter.

    Adding a cast would have also worked but it would have caused a lot of warnings for unconditional casts. The unconditional cast is actually still there (through the clazz parameter), but this allows to easily identify all callers that need a cast as they use the method with 2 parameters.

    Additionally – and this is very specific to this case – it appeared that the param itself was often the result of a method call on some TypedParam<T> where T was the expected return type of getVal(), and which also contained T's class.

    I could thus implement an additional convenience method:

        public static <T> T getVal(TypedParam<T> param) {
            return getVal(param.stringValue(), param.getValueClass());
        }
    

    and replaced all getVal(param.stringValue()) by just getVal(param).

    This solution does not resolve the general casedetect overloaded method calls that would differ between Java 7 and Java 8 – but it resolves it for methods that are known to cause this problem. And we didn't find it elsewhere since then.

    0 讨论(0)
提交回复
热议问题