java 泛型方法 泛型类型参数,泛型Java方法的泛型是否可以用来强制参数的类型?...

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值