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

前端 未结 2 1922
野性不改
野性不改 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: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 getVal(String param, Class 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 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 getVal(TypedParam 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.

提交回复
热议问题