0
我在设计过滤框架时遇到了泛型的一些问题。 我收到编译错误。我不明白以及如何解决。 我试过但我认为这不是一个完美的方式。 继编译错误设计泛型时遇到的问题
The method filter(String, Filter<Product>) in the type
CollectionMapper3<Product> is not applicable for the arguments
(String, Filter<Object>)
代码:
public interface Filter<T> {
public abstract boolean matches(T object);
}
public abstract class AttributeFilter3<T,C extends Comparable<C>> implements Filter<T> {
String property;
Comparable<C> comparable;
public AttributeFilter3(Comparable<C> comparable) {
this.comparable = comparable ;
}
public void setProperty(String property) {
this.property = property;
}
protected abstract boolean compare(int value);
@Override
public boolean matches(T t) {
return false;
}
public static <T,C extends Comparable<C>> Filter<T> EQUALS(Comparable<C> comparable) {
return new AttributeFilter4<T,C>(comparable) {
@Override
protected boolean compare(int result) {
return result == 0;
}
};
}
}
public class CollectionMapper3<T> {
private Collection<T> collection;
public CollectionMapper3(Collection<T> collection) {
this.collection = collection;
}
@SuppressWarnings("rawtypes")
public final CollectionMapper3<T> filter(String propertyName, Filter<T> filter) {
Collection<T> result = new ArrayList<>();
for (T t : collection) {
if (filter instanceof AttributeFilter3) {
((AttributeFilter3) filter).setProperty(propertyName);
if (filter.matches(t)) {
result.add(t);
}
}
}
collection = result;
return this;
}
public Collection<T> getResult() {
return collection;
}
}
public class Client3 {
public static void main(String[] args) {
Collection<Product> allProducts = MockUtil.getAllProducts();
// Here is the compilation error I am getting
Collection<Product> result = new CollectionMapper3<Product>(allProducts)
.filter("name", AttributeFilter3.EQUALS("sss")).filter("quantityInStock", AttributeFilter3.EQUALS(8))
.getResult();
System.out.println(result);
}
}
public class Product {
private String name;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
@Override
public String toString() {
return name ;
}
}
定义方法的参数,平等相待(C可比)而不是EQUALS(可比) –
Palamino