所以我想这样做:
public interface IFieldObject {
public Comparable get();
}
public interface IFieldCondition {
public boolean apply(IFieldObject field, Comparable compare);
}
public class EqualTo implements IFieldCondition {
public boolean apply(IFieldObject field, Comparable compare) {
return (field.get().compareTo(compare) == 0);
}
}
但是Eclipse给了我警告:
类型安全:方法compareTo(Object)属于raw 类型可比较。参考通用 类型可比较应该是 参数
所以我把它变成了:
public interface IFieldObject {
public Comparable<?> get();
}
public interface IFieldCondition {
public boolean apply(IFieldObject field, Comparable<?> compare);
}
public class EqualTo implements IFieldCondition {
public boolean apply(IFieldObject field, Comparable<?> compare) {
return (field.get().compareTo(compare) == 0);
}
}
由于以下原因而无法编译:
方法compareTo(捕获#1-of?) 在类型可比较 不适用于参数 (比较)
这样做的正确方法是什么? (在惯用Java&gt; = 1.6之后没有警告)
答案 0 :(得分:4)
目前,您无法保证field.get()
返回的类型与该方法指定的类型真正可比。理想情况下,使整个事物变得通用,例如:
public interface IFieldObject<T extends Comparable<T>> {
public T get();
}
public interface IFieldCondition<T> {
public boolean apply(IFieldObject<T> field, Comparable<T> compare);
}
public class EqualTo<T> implements IFieldCondition<T> {
public boolean apply(IFieldObject<T> field, Comparable<T> compare) {
return (field.get().compareTo(compare) == 0);
}
}
毫无疑问,使用额外的捕获可以使这更加通用,但这是起点。
答案 1 :(得分:2)
这个怎么样?
public interface IFieldObject {
public<T> Comparable<T> get();
}
public interface IFieldCondition {
public boolean apply(IFieldObject field, Comparable<?> compare);
}
public class EqualTo implements IFieldCondition {
public boolean apply(IFieldObject field, Comparable<?> compare) {
return (field.get().compareTo(compare) == 0);
}
}