0

In Java, I have a map where keys are Class<BaseType> objects. Each entry is keyed with an object of Class<ExtendedType> where ExtendedType extends BaseType. (There are many different ExtendedType classes, say ExtendedType1, ExtendedType2, etc., and just one BaseType.)

Map<Class<BaseType>, String> myMap;

I know it works on our project. However, I wonder whether this is syntactically correct?

If the syntax is fine, then the following should be fine as well (except for two lines - see comments in code):

class A {
}

class B extends A {
}

public static void main(String[] args) {

  // First inheritance:

  A a = new A();
  // Do something with a.

  B b = new B();
  // Do something with b.

  a = new B();
  // Should be fine since B extends A.

  b = new A();
  // Should NOT compile. A is a superclass of B.


  // Now reflection:

  Class<A> classA = A.class;
  // Do something with classA.

  Class<B> classB = B.class;
  // Do something with classB.

  classA = B.class;
  // Should be fine since Class<B> extends Class<A>. Does it really?

  classB = A.class;
  // Should NOT compile. Class<A> is a superclass of Class<B>. Is it?

}

What do you think? Thanks for any hints/comments.

Pavel Foltyn
  • 175
  • 3
  • 13
  • I don't think your referenced question is a duplicate of this one. The difference is obvious - the question https://stackoverflow.com/questions/2745265/is-listdog-a-subclass-of-listanimal-why-are-java-generics-not-implicitly-po asks about **generics**. My question is mainly about **reflection**. `List` is quite a different thing from `Class`. – Pavel Foltyn Apr 05 '19 at 10:23
  • I'm sorry, you're ultimately right. My question is rather a version of this: https://stackoverflow.com/questions/857420/what-are-the-reasons-why-map-getobject-key-is-not-fully-generic. I was wondering why the following code compiles: `Map, String> myMap = new HashMap<>(); String str = myMap.get(new ExtendedType1());`. Although this code does **not**: `Map, String> myMap = new HashMap<>(); myMap.put(new ExtendedType1(), "Value for ExtendedType1");` – Pavel Foltyn Apr 05 '19 at 12:35

0 Answers0