Java generic type mismatch in method signature

I have a class Executorthat calls interface instances IService<T>with an argument KeyList<T>.

   class Executor{
      KeyList<?> _keys;
      IService<?> _service;
      public Executor(IService<?> service, KeyList<?> keys){
         _service = service;
         _keys = keys;
      }

      public void execute(){
         _service.invoke(_keys);
      }
   }

   interface IService<T>{
      public void invoke( KeyList<T> keys);
   }

   class KeyList<T> {
      List<T> _list;
   }

I used <?>Executor for members, since it doesn't matter how IService and KeyList are parameterized, but the following causes a compilation error in which the arguments are not applicable:

 public void execute(){
    _service.invoke(_keys); //error on invoke
 }

I suppose he complains because he is KeyList<?>not equal KeyList<T>, but <?>coincides with <? extends Object>, so I am a little confused. Is there a better alternative?

+2
source share
2 answers

A wildcard (?) . - . :

class Executor<T> {
    KeyList<T> _keys;
    IService<T> _service;
    public Executor(IService<T> service, KeyList<T> keys){
        _service = service;
        _keys = keys;
    }

    public void execute(){
        _service.invoke(_keys);
    }
}

T Executor, _keys _service, , .

Executor, :

class Executor {

    private static final class ServiceAndKeys<T> {

        private final KeyList<T> keys;
        private final IService<T> service;

        ServiceAndKeys(IService<T> service, KeyList<T> keys) {
            this.service = service;
            this.keys = keys;
        }

        void execute() {
            service.invoke(keys);
        }
    }

    private final ServiceAndKeys<?> serviceAndKeys;

    public <T> Executor(IService<T> service, KeyList<T> keys){
        serviceAndKeys = new ServiceAndKeys<T>(service, keys);
    }

    public void execute() {
        serviceAndKeys.execute();
    }
}
+3

IService<?> _service;

- . a type-1.

KeyList<?> _keys;

- . a type-2.

, , , . Capture Conversion.

Ti (. 4.5.1) ?, Si , Ui [A1: = S1,..., An: = Sn] (§ 4.1).

<?> .

,

KeyList _keys;
IService _service;

.

+2

All Articles