Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java: How to fix the Unchecked cast warning

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?

like image 908
Brad Avatar asked Dec 08 '10 13:12

Brad


People also ask

What is unchecked cast in Java?

Unchecked cast means that you are (implicitly or explicitly) casting from a generic type to a nonqualified type or the other way around.

What is @SuppressWarnings unchecked in Java?

@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.


2 Answers

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)); 
like image 171
Tom Hawtin - tackline Avatar answered Sep 22 '22 17:09

Tom Hawtin - tackline


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.

like image 34
Ralph Avatar answered Sep 20 '22 17:09

Ralph