1

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.

2
  • what do you think this line is supposed to do? <T> ClassInfo<T> getClassInfo(Class<T> c) Commented Nov 28, 2013 at 17:51
  • You can enclose Context<T> and declare the Map with T Commented Nov 28, 2013 at 18:14

2 Answers 2

1

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!

Sign up to request clarification or add additional context in comments.

2 Comments

Doesn't really work. Now there is a compiler error and a compiler warning. The error reads: Type safety: Unchecked cast from ... to .... And the warning reads: Unnecessary @SuppressWarnings("unchecked"). It could be that my eclipse compiler settings are a little bit too restricted.
I enabled the following compiler option of Eclipse: "Suppress optional errors with '@SuppressWarnings'". Now the code is without errors or warnings. But when executing this method, I get an Error exception "Unresolved compilation problem".
1

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

2 Comments

The compiler error changed from "Type mismatch" to "Type safety"... (see first answer)
that is just a warning.. to clear that warning, check my updated answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.