泛型:确保参数具有相同的类型 [英] Generics: Make sure parameters are of same type
问题描述
我有以下方法:
protected <S> void setValue(final S oldValue, final S newValue) {
// Do something
}
我想确保两个参数的类型相同.如果您尝试传递两种不同类型的参数时出现编译器错误,那就太好了.
I want to make sure, that both parameters are of the same type. It would be cool, if there'd be a compiler error when you try to pass parameters of two different types.
以上方法显然不是正确的方法.我可以放入String
和Integer
,因为两者都从Object
延伸.
The above way is clearly not the correct one. I can put into a String
and an Integer
, since the both extend from Object
.
我想要吗?还是确保两个参数具有相同类型的唯一方法是将其检查到方法内部并抛出IllegalArgumentException
?
Is my want even possible? Or is the only way to make sure both parameters are of the same type to check it inside the method and throw an IllegalArgumentException
?
推荐答案
如果您认为S是正确的类型,则可以这样做:
You can do that if you consider that S is the correct type :
protected <S, T extends S> void setValue(final S oldValue, final T newValue) {
// Do something
}
您可以输入,也可以不输入:
You can and can't input these :
// Works
setValue("something", "something");
setValue(new Object(), new String());
// Doesn't work
setValue(new String(), new Object());
或
您可以:
protected <S> void setValue(final S oldValue, final S newValue, final Class<S> clazz) {
// Do something
}
并像这样使用它
setValue("something", "something", String.class);
或
protected <S> void setValue(final S oldValue, final S newValue) {
if(!oldValue.getClass().equals(newValue.getClass())) {
//throw something
}
}
这篇关于泛型:确保参数具有相同的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!