简体   繁体   中英

Java 8 generic type check

In Java 7 different types for the checked method causes compile error, while in Java 8 there is no compile error. Is it possible to keep the generics in checked and make it create compile error in Java 8?

class CheckedEquals{
    public static <T> boolean checked(T expected, T actual) {
       return com.google.common.base.Objects.equal(expected, actual);
    }
}

class ShouldFailAtCompileTime{
    public void foo(){
        if(CheckedEquals.checked("String", Boolean.TRUE)){
            System.err.println("");
        }
    }
}

The behaviour not to cause a compile error is correct here, since the generic type parameter T is Object . How else should the compiler guess the type parameter if it isn't specified? I wonder how Java 7 did that, as far as I know there were no changes.

This one would lead to a compile error however:

CheckedEquals.<String>checked("String", Boolean.TRUE)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM