Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I would like to use a generic type to ensure, that the arguments of a method are of the same type, like this:

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

I would assume that the two arguments (a and b), that are passed to this method, would always have to be of the same type. But to my surprise I was able to pass arguments of any type (even primitives) to method x, as if T is erased to Object, no matter what arguments are passed.

The only work-around I found so far, was to use 'extends' like this:

public static <T, U extends T> void x(T a, U b) 

But although I can live with it, it is not what I wanted.

Is there a way to use a generic type to force the type of all arguments of a method?

like image 786
sys64738 Avatar asked May 13 '15 14:05

sys64738


People also ask

Are generics type differ based on their type arguments?

Generic Functions: We can also write generic functions that can be called with different types of arguments based on the type of arguments passed to the generic method. The compiler handles each method.

Which of the following statements are true about generic methods in Java?

Which of these is an correct way of defining generic method? Explanation: The syntax for a generic method includes a type parameter, inside angle brackets, and appears before the method's return type. For static generic methods, the type parameter section must appear before the method's return type. 5.


1 Answers

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) {     } } 
like image 197
TNT Avatar answered Oct 16 '22 17:10

TNT