フィルタフレームワークを設計する際にジェネリックスに問題があります。 コンパイルエラーです。私は理解していないし、再解決する方法。 私は与えることを試みたが、私はそれが完璧な方法ではないと思う。コンパイルエラーに続いて デザイン時にジェネリックスで問題が発生する
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と同等)の代わりに等価(相当) –
Palamino