So I got an interface SuperType and a bunch of implementing classes TypeA, TypeBand so on. I also got a top-level interface which has a parameterized method:
public interface UsedByProductThing<T extends SuperType> {
public T doStuff(T one);
}
I got a factory (see below) producing objects implementing GeneralProduct:
public interface GeneralProduct<T extends SuperType> {
T doSomething(T input);
}
Here is the implementing ProductA:
public class ProductA implements GeneralProduct<TypeA> {
UsedByProductThing<TypeA> in;
public ProductA(UsedByProductThing<TypeA> in) {
this.in = in;
in.doStuff(new TypeA());
}
@Override
public TypeA doSomething(TypeA input) {
return null;
}
}
And now the factory in question:
public class GeneralFactory {
public static <T extends SuperType> GeneralProduct<T> createProduct(
int type, UsedByProductThing<T> in) {
switch (type) {
case 1:
return (GeneralProduct<T>) new ProductA((UsedByProductThing<TypeA>) in);
// at this point, i want to return a "new ProductA(in)" preferably
// without casting
// or at least without the cast of the argument.
default:
throw new IllegalArgumentException("type unkown.");
}
}
}
As commented, I want that factory-method to not use a cast. I understand that the return type has to be GeneralProduct, but I can’t think of a way omitting the cast (and it gives me an “unchecked cast”-warning, too). Also, I can’t think of a way omitting the cast of the argument. I’m able to restructure the whole code if it’s necessary to get rid of the “unsafe” casting at that place. Can you tell me a way that would be nice and smooth here?
Also, please edit my question as you like – I don’t know how to adress the issue correctly in the title.
Thanks a lot!
You can’t avoid casting because
inwhich has typeUsedByProductThing<T>which you want to turn into aUsedByProductThing<TypeA>and the compiler has no way of knowing thatTisTypeAGeneralProduct<TypeA>and again the compiler doesn’t know thatTis aTypeAhere either.The only way to avoid cast is to replace
TwithTypeA