问题
So I want to do this:
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);
}
}
but Eclipse gives me warnings:
Type safety: The method compareTo(Object) belongs to the raw type Comparable. References to generic type Comparable should be parameterized
So I turned this into:
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);
}
}
which does not compile because of:
The method compareTo(capture#1-of ?) in the type Comparable is not applicable for the arguments (Comparable)
What's the right way to do that ? (without warnings following idiomatic Java >= 1.6)
回答1:
How about this?
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);
}
}
回答2:
Currently you've no guarantee that the type returned by field.get() is really comparable with the type specified by the method. Ideally, make the whole thing generic, e.g.:
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);
}
}
You could no doubt make this more general using extra captures, but that's the starting point.
来源:https://stackoverflow.com/questions/5872251/java-generics-the-method-comparetocapture1-of-in-the-type-comparablecapt