user414967 user414967 - 1 month ago 15
Java Question

issue with Generics while designing

I am facing some issues in Generics while designing a filter framework.
I am getting compilation error. I dont understand and how to ressolve.
I tried giving but I think that is not a perfect way.
Following the compilation error

The method filter(String, Filter<Product>) in the type
CollectionMapper3<Product> is not applicable for the arguments
(String, Filter<Object>)


Code:

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 ;
}

}

Answer

You don't provide anything from which to infer T when you invoke AttributeFilter3.EQUALS("sss"), so Java will use Object.

You can either provide type parameters:

AttributeFilter3.<String, String>EQUALS("sss")

or you can update the method signature to accept a type token:

public static <T,C extends Comparable<C>> Filter<T> EQUALS(Comparable<C> comparable, Class<T> ignored) {

then

AttributeFilter3.EQUALS("sss", String.class)
Comments