Setup:
I have an interface for some formats:
interface Formatter<T extends AbstractItem> { String format(T item); }
I have a factory creating such formats:
public class Factory { public static Formatter<? extends AbstractItem> create() { switch (something) { case SOMETHING: return new Formatter<SomeItem>() { String format(SomeItem item) {...}}; case SOMETHING_ELSE: return new Formatter<OtherItem>() { String format(OtherItem item){...}}; }
Now I use this factory to get formatting, and I use it:
1: Formatter formatter = Factory.create(); 2: for (AbstractItem item : items) { 3: formatter.format(item); 4: }
The items list contains only the subtexts of AbstractItem that formatter can handle.
Problem:
I get two warnings:
Line 1: Formatter is a raw type. References to generic type Formatter<T> should be parameterized. Line 3: Type safety: The method format(AbstractItem) belongs to the raw type Formatter. References to generic type Formatter<T> should be parameterized.
OK, so I'm trying to fix the first one: I know that the factory is returning something from AbstractItem :
1: Formatter<? extends AbstractItem> formatter = Factory.create();
Now the warning on line 1 disappears, but a new error occurs on line 3:
Line 3: The method format(capture
So, if I understand correctly, he complains that AbstractItem not a subtype of AbstractItem (as required by the <? extends AbstractItem> constraint type). Fair enough, but AbstractItem is abstract, so item I go to formatter , always has some type extending AbstractItem ...
How to explain this to the compiler? For now, I decided to go with @SuppressWarnings ...
java generics factory
vektor
source share