Java generic field declaration

As a note it is possible to declare a class type as a field (since google sends me here for this unrelated question...)

  Class<? extends MyInterface> myCurrentClass = MyImplementation.class;

You can not do it directly on the field, but you can maintain your types policy by generic methods (they can exist even in non-generic class):

@SuppressWarnings("rawtypes")
private Map<Class, List> map;

public <T extends Serializable> void put(Class<T> key, List<Consumer<? extends T>> value) {
    map.put(key, value);
}

@SuppressWarnings("unchecked")
public <T extends Serializable> List<Consumer<? extends T>> get(Class<T> key) {
    return map.get(key);
}

You have to somewhere introduce the type-parameter, so that you can use them in the definition for your class members.

Introducing a type-parameter can be done only on a class-level, or on a method-level. In your case, it should be on class-level:

public class Client<T extends Serializable, S extends T> {
    private Map<Class<T>, List<Consumer<S>>> classToConsumerTry1;

    private Map<Class<T>, List<Consumer<S>>> classToConsumerTry2;
}

This, however, implies that for both members (classToConsumerTry1 and classToConsumerTry2), T and S are the same. If you want them to be different, the you will have to get these two values from two different classes, both of which are parameterized with separate type-parameters.


You can't. Your only option is to declare the generic type parameters in your Client class declaration. If your Client class has no generic type parameters, its members can't be generic. You must use actual types in the declaration of your class members.