【发布时间】:2017-10-25 10:53:54
【问题描述】:
有什么方法可以在具体方法中使类类型参数更窄(添加另一个绑定)?
我们来看例子
public class Value<T>
{
private final T value;
public Value(T value)
{
this.value = value;
}
public <V extends T> boolean eq(V value)
{
return Objects.equals(this.value, value);
}
// here, I want to create bound that T extends Comparable<T>
// error: type parameter cannot be followed by other bounds
public <V extends T & Comparable<T>> boolean gt(V value)
{
return ((V)this.value).compareTo(value) > 0;
}
// here, I want to create bound that T extends String
// error: interface expected here
public <V extends T & String> boolean match(V value)
{
return ((V)this.value).equalsIgnoreCase(value);
}
public static void main(final String[] args)
{
final Value<Integer> integerValue = new Value<>(10);
integerValue.eq(10); // should compile
integerValue.gt(5); // should compile
integerValue.match("hello"); // shouldn't compile because match operates only on String values
final Value<String> stringValue = new Value<>("Foo");
stringValue.eq("Foo"); // should compile
stringValue.gt("bar"); // should compile
stringValue.match("foo"); // should compile
}
}
在此示例行中
integerValue.match("hello");
不编译,这是正确的,但是由于类型参数不能跟随其他边界
的限制,该类也无法编译还有其他方法可以实现吗?
【问题讨论】: