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 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 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?
解决方案
If I understand your question correctly, you want this:
x(10, "x");
to fail at compile time.
Now consider doing this:
Integer i = 10;
String s = "x";
Object o1 = i;
Object o2 = s;
x(o1, o2);
In this case they are both objects - the same type. I don't think there is any way to really enforce what you want - when you cast your argument to Object it is always possible to call it with two different types without any warnings/errors.
You can specify the type you want to use by using it like this:
ClassName.x(obj1, obj2);
And it's proably the only way to do it.