Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forcing two parameters of a generic method to have the same concrete type

How can I have a method with two parameters, with both parameters having the same concrete type?

For example,

boolean equals(Object a, Object b)

allows for a of any type and b of any type.

I want to force such that a and b have the same concrete type. I tried

<T> boolean equals(T a, T b)

and inputting a Date and a String to that method, expecting a compile-time error, but I get no errors, since T will resolve to ? extends Serializable & Comparable, since both Date and String implements Serializable and Comparable.

like image 865
Randy Sugianto 'Yuku' Avatar asked Sep 16 '14 11:09

Randy Sugianto 'Yuku'


1 Answers

You can't, basically. There's no way of doing that. Even if you could do it for a simple call to prohibit arguments of different types, it could always be bypassed using a cast:

equals((Object) date, (Object) string)

If you're interested in the execution-time types of the arguments, you can only test that at execution time. There's no way of the compiler knowing whether an argument of type Date has a value which is a reference to precisely a java.util.Date or some subclass.

like image 112
Jon Skeet Avatar answered Oct 05 '22 23:10

Jon Skeet