简体   繁体   中英

Generic type parameter which implements generic interace

In a Java application, I'd like to use a generic type parameter which implements an interface which uses a generic parameter itself.

public interface SuperInterface<T> { ... }

public interface MyInterface extends SuperInterface<MyClass> { ... }


public class Worker<T extends SuperInterface<U>> extends SuperWorker<String, Boolean> {

}

However, the class declaration won't work like that. T should be of type MyInterface (or any other interface which implements the SuperInterface) and U should be of type MyClass (or any other class according to the interface).

You have to declare all of the type parameters at the top level. It's annoying, but that's how it is.

public class Worker<U extends MyClass, T extends SuperInterface<U>> { ...

The order of the parameters doesn't matter; you can also do Worker<T extends..., U extends...> . All that matters is that each is declared at the top level of the nested generics.

Here's a complete class:

public class MyClass {
  public interface SuperInterface<T>{}

  public interface MyInterface extends SuperInterface<MyClass> {}

  public class Worker<U extends MyClass, T extends SuperInterface<U>> {}

  public void compileTest() {
    // just to make sure the declaration compiles
    Worker<MyClass, MyInterface> worker = null;
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM