泛型:确保参数的类型相同
我有以下方法:
protected <S> void setValue(final S oldValue, final S newValue) {
// Do something
}
我想确保两个参数的类型相同。如果当您尝试传递两种不同类型的参数时出现编译器错误,那就太酷了。
上面的方式显然不是正确的方式。我可以放入一个String
和一个Integer
,因为它们都是从Object
扩展的。
我的愿望可能实现吗?或者是确保两个参数具有相同类型的唯一方法,以便在方法内检查它并抛出 IllegalArgumentException
?
I've got the following method:
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.
The above way is clearly not the correct one. I can put into a String
and an Integer
, since the both extend from Object
.
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
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您认为 S 是正确的类型,则可以这样做:
您可以也不能输入这些:
或
您可以这样做:
并像这样使用它
或
You can do that if you consider that S is the correct type :
You can and can't input these :
or
You can do :
and use it like that
or
恐怕这实际上是不可能的,除非进行明确的检查。它总是会被强制为
Object
;没有办法阻止输入被强制为超类型。您可以在参数验证中使用显式的基于反射的检查,但这只是您唯一的选择。
This isn't really possible, I'm afraid, except for explicit checks. It'll always get coerced up to
Object
; there's no way to stop inputs from getting coerced up to supertypes.You can use explicit reflection-based checking in your argument validation, but that's just about your only option.