我有一个这样的界面:
public T evaluate(float fraction, T startValue, T endValue);
其他代码会将每个T
类型视为Object
,最后我会获得返回值,这也是Object
类。
我想要的是将startValue
和endValue
作为整数传递,但返回一个完全不同的实例(不是Integer
)。我会强制将返回值转换为我想要的值。
我所做的是用对象替换T
,如下所示:
public Object evaluate(float fraction, Object startValue, Object endValue)
但这失败了,我想如果定义为? extends T
的界面会起作用,但事实并非如此。 (我是对的吗?)
那么有什么办法可以绕过泛型类型检查吗?
答案 0 :(得分:4)
假设您的界面具有T通用参数,请添加第二种类型,例如R:
interface MyInterface<T,R> {
public R evaluate(float fraction, T startValue, T endValue);
}
答案 1 :(得分:0)
我想你有一个像interface Name<T>{}
这样的界面。
为什么不让T
成为Integer
,然后将返回的内容转换为您想要的内容。 (如果我想得到一个字符串):
//interfaceInstance is Name<Integer>
//fraction is float, startValue and endValue are Integer
String value = String.valueOf(interfaceInstance.evaluate(fraction, startValue endValue))