0

I have the following code snippet which returns a type mismatch error:

@SuppressWarnings("rawtypes")
public Map<String, Class<? extends SomeClass.SuperClass>> subClass() {
    return Collections.singletonMap("hello", SomeClass.SubClass.class);
}

The class declaration looks like the following:

public class SomeClass {

    public static abstract class SuperClass { }

    public static class SubClass extends SuperClass{ }
}

This returns a type mismatch error, stating:

Type mismatch: cannot convert from Map<String,Class<SubClass>> to Map<String,Class<? extends SuperClass>>

Why is this occurring? Regardless of whether I use "? extends SuperClass" or just "SuperClass" in the parameterized return type of subClass(), I still see this same error. I've also tried just extending SomeClass instead but that hasn't worked either.

0

2 Answers 2

2

Your SubClass is subtype of SuperClass, but Map<String, Class<SubClass>> isn't subtype of Map<String, Class<SuperClass>>. For more information you can see Generics, Inheritance, and Subtypes

For Java SE 7 you can use:

return Collections.<String, Class<? extends SomeClass.SuperClass>>singletonMap("hello", SomeClass.SubClass.class);
Sign up to request clarification or add additional context in comments.

2 Comments

Explicit type parameter is a good point, can Java 8 be calling that automatically?
This are Type inference and Target Typing stuff.
2

I think there is a typo. It should be:

@SuppressWarnings("rawtypes")
    public Map<String, Class<? extends SomeClass.SuperClass>> subClass() {
        return Collections.singletonMap("hello", SomeClass.SubClass.class);
    }

You missed .class :)


In Java, generics are invariant. This means if:

Dog extends Animal then List<Dog> does not extend List<Animal>

List<Animal> ls = new ArrayList<Dog>() //illegal

Hence this is invalid code and doesn't work:

Map<String, Class<SomeClass.SuperClass>> hello2 = Collections.singletonMap("hello", SomeClass.SubClass.class);

And this is perfectly alright:

Map<String, Class<? extends SomeClass.SuperClass>> hello = Collections.singletonMap("hello", SomeClass.SubClass.class);
return hello;

6 Comments

That still gives the Type mismatch error in Netbeans.
I am using Java8. And it compiles fine on mine.
I have Java 7 (1.7.0_67)
So is this only a Java 8 feature? I'm looking into it
I read the Java 8 whats new page but did not see anything new that might cause this. I thought it might be Netbeans so compiled with javac and Ideone, both did not compile.
|

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.