Łukasz Woźniczka
Łukasz Woźniczka

Reputation: 1695

java generic class cast

Hello i have got hash map with value:

    private static final LinkedHashMap<Class<? extends Annotation> , Class<? extends AGenerator<?>>> annotationGeneratorMap = new LinkedHashMap<Class<? extends Annotation>, Class<? extends AGenerator<?>>>();

and my numeric Generator looks like :

public abstract class NumericGenerator<T extends Number> extends AGenerator<T>{


public NumericGenerator(Field field) {
    super(field);
    // TODO Auto-generated constructor stub
}

public T random() {
    // TODO Auto-generated method stub
    return null;
}

  }

And i have got problem when i need to put this class into hashmap :

annotationGeneratorMap.put(GenerateNumeric.class, NumericGenerator.class);

And in eclipse i have got error the method is not applicable for the argument ???

but :

        annotationGeneratorMap.put(GenerateNumeric.class, (Class<? extends AGenerator<?>>) NumericGenerator.class);

and @SuppressWarnings("unchecked") is good ..:/

Can i do this without casting ?? (Class<? extends AGenerator<?>>) NumericGenerator.class

Upvotes: 3

Views: 1940

Answers (3)

Miserable Variable
Miserable Variable

Reputation: 28752

Following compiles without error on version 1.7.0_02:

import java.util.*;
import java.lang.annotation.*;

interface AGenerator<T> {}

interface A extends Annotation {}
class X implements AGenerator<X> {}

class E7 {
    private static final LinkedHashMap<Class<? extends Annotation>, 
        Class<? extends AGenerator<?>>> annotationGeneratorMap 
        = new LinkedHashMap<Class<? extends Annotation>, 
                            Class<? extends AGenerator<?>>>();


    void foo() {
        annotationGeneratorMap.put(A.class, X.class);
    }

}

Upvotes: 1

nullpotent
nullpotent

Reputation: 9260

Compile time check won't allow you to do that unless you cast it of course.

Information about generic types is lost at runtime, not compile time.

Upvotes: 1

irreputable
irreputable

Reputation: 45433

use Class<? extends AGenerator> instead

LinkedHashMap<
    Class<? extends Annotation>, 
    Class<? extends AGenerator> > annotationGeneratorMap = new LinkedHashMap<>()

In Java, class can represent a raw type, but cannot represent a generic type.

There is a class for List, but there is no class for List<String>.

So you can declare Class<? extends List>, which is compatible with ArrayList.class etc. because raw type ArrayList is a subtype of List.

But Class<? extends List<?>> doesn't make much sense, because there is no class that is a subtype of List<?>.

And all thanks to erasure.

Upvotes: 2

Related Questions