I've got the following code:
private HashMap<Class<?>, HashMap<Entity, ? extends Component>> m_componentStores; public <T extends Component> T getComponent(Entity e, Class<T> exampleClass) { HashMap<Entity, ? extends Component> store = m_componentStores.get(exampleClass); T result = (T)store.get(e); if (result == null) { throw new IllegalArgumentException( "GET FAIL: "+e+" does not possess Component of class\nmissing: "+exampleClass ); } return result; }
When I compile, it shows that T result = (T)store.get(e)
has an unchecked cast.
Type safety: Unchecked cast from capture#2-of ? extends Component to T
What am I missing to prevent this warning from appearing?
Unchecked cast means that you are (implicitly or explicitly) casting from a generic type to a nonqualified type or the other way around.
@SuppressWarnings("unchecked") is used when Java generics just don't let you do what you want to, and thus, you need to explicitly specify to the compiler that whatever you are doing is legal and can be executed at the time of execution.
Class.cast
is what you want. Well, you might consider not using reflection.
Change the line:
T result = (T)store.get(e);
to:
T result = exampleClass.cast(store.get(e));
Write @SuppressWarnings("unchecked")
above the Cast statement:
@SuppressWarnings("unchecked") T result = (T)store.get(e);
And add a explanatory statement why it is safe to ignore the warning.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With