In a abstract factory pattern i am using generics. I have BaseEntity interface which extends Serializable, the Employee class implements the BaseEntity. In the abstract class i have this getJavaObj method
getJavaObj()
is a method which takes a Long empId
and returns a Map<String, ? extends BaseEntity>
public abstract Map<String, ? extends BaseEntity> getJavaObj(Long id);
Using generics i am trying to do this in the main class it gives;
Map<String, Employee> emp = getJavaObj(empId);
It gives this error Type safety: Unchecked cast from Map<String,capture#1-of ? extends BaseEntity>
to Map
When i do the type casting like this
Map<String, Employee> emp = (Map<String, Employee>)getJavaObj(empId);
It gives this warning
Type safety: Unchecked cast from
Map<String,capture#1-of ? extends Serializable>
to Map Type safety: Unchecked cast fromMap<String,capture#1-of ? extends BaseEntity>
to Map
Is there a way to avoid type-casting or resolve the warnings even after typecasting? Since the object i am returning does extend to the Serializable via BaseEntity interface.
Redefine your factory method:
public abstract <T extends BaseEntity> Map<String, T> getJavaObj(Long id);
Then you can get the correct type back without a cast:
Map<String, Employee> emp = getJavaObj(empId);