本文介绍了Java通用问题:“不兼容的类型;推断的类型实参(s)java.lang.Object不符合类型变量(s)T的边界的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下简单的程序使用Eclipse编译器编译,但不编译为Javac:
public class Test {
public static interface函数< T1,T2,Boolean> {
布尔适用(T1 t1,T2 t2);
}
private static< T extends Comparable< T>>函数< T,T,Boolean> _cmp(final boolean lt){
return new Function< T,T,Boolean>(){
@Override
public Boolean apply(T t1,T t2){
if (lt){
return(t1.compareTo(t2)} else {
return(t1.compareTo(t2)> 0);
}
}
};
}
public static Function LESS_THAN = _cmp(true); //错误行
public static Function GREATER_THAN = _cmp(false); // error line
}
Javac的错误消息: p>
java:P:\java-tool\src\main\java\T3.java:20:不兼容的类型;推断的类型实参java.lang.Object不符合类型变量的边界T
found:< T> T3.Function< T,T,java.lang.Boolean>
required:T3.Function
解决方案
推理不适用于版本1.6 -
尝试手动指定类型参数。例如。 -
public static Function LESS_THAN = Test。< Integer> _cmp(true); //错误行
请注意,您正在使用您自己的泛型类的原始版本。 p>
The following simple program compiles with Eclipse compiler, but not Javac:
public class Test {
public static interface Function<T1, T2, Boolean> {
Boolean apply(T1 t1, T2 t2);
}
private static <T extends Comparable<T>> Function<T, T, Boolean> _cmp(final boolean lt) {
return new Function<T, T, Boolean>() {
@Override
public Boolean apply(T t1, T t2) {
if (lt) {
return (t1.compareTo(t2) < 0);
} else {
return (t1.compareTo(t2) > 0);
}
}
};
}
public static Function LESS_THAN = _cmp(true); // error line
public static Function GREATER_THAN = _cmp(false); // error line
}
The error message of Javac:
java: P:\java-tool\src\main\java\T3.java:20: incompatible types; inferred type argument(s) java.lang.Object do not conform to bounds of type variable(s) T
found : <T>T3.Function<T,T,java.lang.Boolean>
required: T3.Function
解决方案
The type inference is not working for version 1.6 -
Try manually specifying the type argument. E.g. -
public static Function LESS_THAN = Test.<Integer>_cmp(true); // error line
Note that you are using the raw version of your own generic class there.
这篇关于Java通用问题:“不兼容的类型;推断的类型实参(s)java.lang.Object不符合类型变量(s)T的边界的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!