强制泛型方法的两个参数具有相同的具体类型 [英] Forcing two parameters of a generic method to have the same concrete type
问题描述
我怎样才能得到一个有两个参数的方法,这两个参数具有相同的具体类型?
How can I have a method with two parameters, with both parameters having the same concrete type?
例如,
For example,
boolean equals(Object a, Object b)
允许任何类型的 a
和任何类型的 b
。
allows for a
of any type and b
of any type.
我想强制 b
具有相同的具体类型。我试过
I want to force such that a
and b
have the same concrete type. I tried
<T> boolean equals(T a, T b)
并输入 Date
和一个
String
给该方法,期待编译时错误,但是我没有错误,因为T会解析为?扩展了Serializable& Comparable
,因为 Date
和 String
implements Serializable
和
Comparable
。
and inputting a Date
and a String
to that method, expecting a compile-time error, but I get no errors, since T will resolve to ? extends Serializable & Comparable
, since both Date
and String
implements Serializable
and Comparable
.
推荐答案
,基本上。没有办法做到这一点。即使你可以通过一个简单的调用来禁止不同类型的参数,也可以使用一个强制类型绕过:
You can't, basically. There's no way of doing that. Even if you could do it for a simple call to prohibit arguments of different types, it could always be bypassed using a cast:
equals((Object) date, (Object) string)
如果你对执行时间类型的参数,你只能在执行时测试它。编译器无法知道 Date
类型的参数是否具有正确引用的值 a java .util.Date
或一些子类。
If you're interested in the execution-time types of the arguments, you can only test that at execution time. There's no way of the compiler knowing whether an argument of type Date
has a value which is a reference to precisely a java.util.Date
or some subclass.
这篇关于强制泛型方法的两个参数具有相同的具体类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!