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

前端 未结 2 1952
野性不改
野性不改 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条回答
  •  萌比男神i
    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 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.

提交回复
热议问题