Is there a way to avoid using @SuppressWarnings below and to keep the same functionality without the warning ‘Type safety: Unchecked cast from AbstractDO[] to E[]’:
public MyClass {
...
private Map<Class<? extends AbstractDO>, AbstractDO[]> map;
...
private void saveConcreteDOs(AbstractDO[] theEntities) {
entityMap.put(theEntities[0].getClass(), theEntities);
}
@SuppressWarnings("unchecked")
protected <E extends AbstractDO> E[] getConcreteDOs(Class<E> theType) {
return (E[]) map.get(theType);
}
...
}
Maybe enhance map declaration?
You have a choice: either suppress the warning for a cast you know will always succeed, or avoid the warning and verify that the cast succeeded with a try/catch block.
There are only those two choices.
In your case, I’d say you have a few options.
I think your best bet is to add a
throws ClassCastExceptionclause to yourgetConcreteDOsmethod and let the caller deal with an invalid cast brought on by an invalid use of the method — assuming they could get it to compile around yourextends AbstractDOclause. This has the unfortunate side effect of forcing the consumer to wrap the call in a try/catch block or declare their own throws clause to force a try/catch block higher up the stack.You could just swallow the exception with an empty catch block; frankly I’d prefer the @SuppressWarning over that.
Or you could drop the method entirely and only deal in abstract entities, effectively making the consumer of your repository deal with the cast.
Bottom line: you’re going to have these issues whenever you try to build generic repositories. You might be better off with a concrete-repository-per-entity-type pattern.