I got a Java function with the following signature:
public void foo(Class<? extends Base1> varClass1, Class<? extends Base2> varClass2) {
// ...
}
In this function, I need to instantiate a HashMap with type:
Map<varClass1, varClass2> map = new HashMap<>();
Of course, this doesn't compile, but I can't think of any other way to make it compile. I was surprised that even the following doesn't work:
Map<Class<? extends Base1>, Class<? extends Base2> map = new HashMap<>();
Of course, I can do:
Map<Base1, Base2> map = new HashMap<>();
But by that I loose any additional fields introduced in the sub-classes. In reality, the use-case is more complex than HashMap. I instantiate a generic class and need to work with all fields of the specified classes, so something like:
GenericClass<varClass1, varClass2> clazz =
new GenericClass<>(varClass1.cast(var1), varClass2.cast(var2));
Aucun commentaire:
Enregistrer un commentaire