javajava-12

Java multiple generics in interface and classes


I'm working in a complex project with a lot of extensions and a lot generics. We use open jdk 12.

The objects I'm working on are:

public abstract class Node<C extends Node, P extends Property, A extends AuthorizationEntry> 

public abstract class Device<D extends Device, DP extends DeviceProperty> extends Node<D, DP, DeviceAuthorizationEntry>

The interface:

public interface NodeValidatorService<P extends Property, A extends AuthorizationEntry, C extends Node<C, P, A>>

The abstract class:

public abstract class AbstractNodeValidatorService<P extends Property, A extends AuthorizationEntry, C extends Node<C, P, A>> implements NodeValidatorService<P, A, C>

The implementation:

public class DeviceValidationServiceBean<D extends Device, DP extends DeviceProperty> extends AbstractNodeValidatorService<DP, DeviceAuthorizationEntry, D>

This last class is the one not compiling, due to:

type argument D is not within bounds of type-variable C

I'm wondering if in DeviceValidationServiceBean I cannot add a further generic or if generics cannot recognize that even if D does not extends directly Node, it is still a Node itself too. Can you explain what I did wrong or if it cannot simply be done that kind of multiple extensions on generics?


Solution

  • Your AbstractNodeValidatorService is declared with this as the last extend:

     C extends Node<C, P, A>> implements NodeValidatorService<P, A, C>
    

    So it expects a C implementation as the last param.

    But your AbstractNodeValidatorService is finishing with a D:

    extends AbstractNodeValidatorService<DP, DeviceAuthorizationEntry, D> //this
    

    D is unrelated to C, so D can't be the last param of the AbstractNodeValidatorService, but a C type class.