Reputation: 11
How do I stop the compiler from complaining at map.get()?
"Type mismatch: cannot convert from ClassInfo<capture#1-of ?> to ClassInfo<T>"
class Context
{
final private Map<Class<?>,ClassInfo<?>> map = new HashMap<>();
<T> ClassInfo<T> getClassInfo(Class<T> c)
{
ClassInfo<T> ci = map.get(c);
if (ci == null) {
ci = new ClassInfo<T>(c);
map.put(c, ci);
}
return(ci);
}
}
Some more information:
ClassInfo contains data about Class, gathered via reflection.
The compiler error does NOT occur with the JDK javac, only when using the Eclipse compiler.
Upvotes: 1
Views: 1606
Reputation: 14520
Just cast it and use :
@SuppressWarnings("unchecked")
ClassInfo<T> ci = (ClassInfo<T>) map.get(c);
Make sure that you are putting Type T into the hash map other wise casting exception can happen.
That is if T represents String, then map.get(c) should always return either null or ClassInfo
Upvotes: 1
Reputation: 17574
I fixed the problem adding a ()cast to the code:
import java.util.HashMap; import java.util.Map;
class Context
{
private final Map<Class<?>,ClassInfo<?>> map = new HashMap<Class<?>,ClassInfo<?>>();
<T> ClassInfo<T> getClassInfo(Class<T> c)
{
@SuppressWarnings("unchecked")
ClassInfo<T> ci = (ClassInfo<T>) map.get(c);
if (ci == null) {
ci = new ClassInfo<T>(c);
map.put(c, ci);
}
return(ci);
}
}
Be aware though, casts are usually dangerous, and you should only use them if you are really sure that object is in fact what you are expecting.
The downside of this solution is that it will create a warning, which I had to suppress. Hope it helps!
Upvotes: 1