简体   繁体   中英

Java: Generics and inheritance

I am building a class Bootstrap for bootstrapping other classes that implement Bootstrappable.

// interface that every class must implement that needs to be bootstrapped
class Bootstrappable implements Runnable {
  public foo();
}

class MyApp implements Bootstrappable {
  public void foo() {}
}

class Bootstrap {
  private Bootstrappable instance;

  public bootstrap(Class<Bootstrappable> b) {
    instance = b.newInstance();
    ...
  }
}

But then I get a compiler error if I try to pass MyApp.class into Bootstrappable.class.

new Bootstrap().bootstrap(MyApp.class);

The method bootstrap(Class Bootstrappable ) in the type Bootstrap is not applicable for the arguments (Class MyApp)

I think is is because inheritance is not for generics. Any way I can handle this?

如果你需要一个实现Bootstrappable的类,你应该定义它的类型如下:

Class<? extends Bootstrappable>

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