Fireburn
Fireburn

Reputation: 1021

Unable to put Class into a generic Map

Here's a visual of the problem:

enter image description here

As can be seen from the visual, the IDE is showing a compile-time error to which it does not allow the class to be inserted into the Map.

Here's a simplified version:

  @Override
  public <T extends Comparable> void transactPersistentEntityStore(...) {
    Map<Class<T>, ComparableBinding> propertyTypeMap = new HashMap<>();
    propertyTypeMap.put(EmbeddedArrayIterable.class, EmbeddedEntityBinding.BINDING);
    propertyTypeMap.put(EmbeddedEntityIterable.class, EmbeddedEntityBinding.BINDING);
    // ...
  }

Even if both EmbeddedArrayIterable and EmbeddedEntityIterable implements Comparable

Am I missing or misunderstanding something on generics?

Upvotes: 1

Views: 225

Answers (1)

Donat
Donat

Reputation: 4813

You can simplify the point of the problem to this code snippet:

public <T extends Comparable> void m1(T x) {
  Class<? extends Comparable> x1Class = x.getClass();
  Class<T extends Comparable> x2Class = x.getClass();
}

Or even to this:

public <T> void m2(T x) {
  Class<?> x1Class = x.getClass();
  Class<T> x2Class = x.getClass();
}

The line with the variable x2Class has an error in these methods. This is because the compiler throws away the Generics and thus there is no type T at runtime. T is not reifiable. You cannot obtain the type T at runtime.

Have also a look at this article: Why following types are reifiable& non-reifiable in java?

Upvotes: 2

Related Questions