泛型Java方法的泛型是否可以用来强制参数的类型? [英] Can the generic type of a generic Java method be used to enforce the type of arguments?

查看:197
本文介绍了泛型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 <T> void x(T a, T b)

我假设两个参数(a和b) ,传递给这个方法的东西总是必须是相同的类型。但令我惊讶的是,我能够将任何类型的参数(甚至是原语)传递给方法x,就好像T被擦除为Object,不管传递了什么参数。

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.

到目前为止我发现的唯一解决方法是使用'extends'像这样:

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?

推荐答案

如果我正确理解你的问题,你需要:

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);

在这种情况下,它们都是对象 - 相同的类型。我不认为有什么办法可以真正实现你想要的 - 当你将参数转换为Object时,总是可以用两种不同的类型调用它,而不会有任何警告/错误。

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.<Type>x(obj1, obj2);

而且它可能是唯一的方法。

And it's proably the only way to do it.

这篇关于泛型Java方法的泛型是否可以用来强制参数的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆