Can the generic type of a generic Java method be used to enforce the type of arguments?

If I understand correctly, one way to do it is to explicitly specify the type of T instead of letting the compiler infer its type to be of the most direct superclass in the case of two objects of different types being passed in as arguments. Take something like this, for example:

public class Test {
    public static void main(String[] args) {
        Test.x(5.0, 5);          // This works since type is inferred to be Number
        Test.<Integer>x(5, 5);   // This works since type is stated to be Integer
        Test.<Integer>x(5.0, 5); // This doesn't; type is stated to be Integer and Double is passed in
    }

    public static <T> void x(T a, T b) {
    }
}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)