0

The type Class<T> is has one generic parameter, namely the type of that class an object represents, which makes perfect sense.

However, when working with the class object of a type that has generic parameters itself, e.g. List<T>, we can handle that in two possible ways:

  1. We refer to that as Class<List<MyType>>, which doesn't make sense: The generic parameter of List loses its meaning since we just refer to its (static) class. Even Class<List<?>> looks conceptually wrong to me.
  2. We just leave out the inner parameter and refer to it as Class<List>. But in this case, the compiler will generate a warning, since it detects List as non-parameterized.

First I thought, that compilers are not smart enough to handle this case correctly, but I guess the original reason has a conceptual nature.

Is there a clean solution for this problem? If not, what would be the best handling in your opinion? Inserting a @SuppressWarnings("rawtypes") or using Class<List<?>>?

Update

I'm facing this problem on some code where the user should be able to provide a custom class for a database connection. This class should extend DoodleDatabaseMap<T>, which is an abstract class and implements Map<String, T>.

I think above description isn't precise enough. It gets hairy when I need to save pass class objects or assign them to a variable. My API method looks as follows:

public static void setDatabaseMap(Class<? extends DoodleDatabaseMap> databaseMap) {
    // ...
}

Giving a generic type to DoodleDatabaseMap here will cause a compile error when calling it (FileDatabaseMap extends DoodleDatabaseMap):

DoodleDebug.setDatabaseMap(FileDatabaseMap.class);

This causes an error message: The method setDatabaseMap(Class<? extends DoodleDatabaseMap<?>>) in the type DoodleDebug is not applicable for the arguments (Class<FileDatabaseMap>)

sepp2k
  • 363,768
  • 54
  • 674
  • 675
Cedric Reichenbach
  • 8,970
  • 6
  • 54
  • 89

1 Answers1

2

This class should extend DoodleDatabaseMap, which is an abstract class and implements Map

Then you could change this

static void setDatabaseMap(@SuppressWarnings("rawtypes") 
    Class<DoodleDatabaseMap> databaseMap)

to use the wildcard capture-of type like

static void setDatabaseMap(Class<DoodleDatabaseMap<?>> databaseMap)
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249