如何在泛型和继承中使用方法? [英] How to use method with generics and inheritance?

查看:55
本文介绍了如何在泛型和继承中使用方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

具有以下课程:

public interface Step<C extends Config> {
  void setConfig(C config);
}

public class ValidationStep implements Step<ValidationConf> {
  public void setConfig(ValidationConf conf) {}
  // implementation
}

public class ProcessStep implements Step<ProcessConf> {
  public void setConfig(ProcessConf conf) {}
  // implementation
}

public interface Config {
  Class<? extends Step> type();
}

public class ValidationConf implements Config {
  public Class<? extends Step> type() {
    return ValidationStep.class;
  }
}

public class ProcessConf implements Config {
  public Class<? extends Step> type() {
    return ProcessStep.class;
  }
}

因此,应用程序需要动态实例化Step子类对象,相应地设置配置并运行该步骤.

so, the application needs to dynamically instantiate Step subclasses objects, set the configuration accordingly and run the step, like this.

List<Config> configs = loadConfigsFromRepository(); // contain all subtypes of Config
for (Config conf: configs) {
  Step<? extends Config> step = conf.type().getDeclaredConstructor().newInstance();

  step.setConfig(conf); // compiler complains

}

错误消息:

"类型中的方法setConfig(capture#8-of扩展Config)步骤<捕获#8- of扩展Config>不适用于arguments(Config)".

"The method setConfig(capture#8-of ? extends Config) in the type Step<capture#8-of ? extends Config> is not applicable for the arguments (Config)".

在这种情况下,检查文档似乎对Java不友好: https://docs.oracle.com/javase/tutorial/java/generics/wildcardGuidelines.html

Checking the documentation, looks like Java won´t be friendly in this case: https://docs.oracle.com/javase/tutorial/java/generics/wildcardGuidelines.html

克服此代码限制的可能解决方案有哪些? step.setConfig(conf); ?

What are the possible solutions to overcome this code restriction step.setConfig(conf);?

已编辑[解决方案]

可以在此处查看代码: https://github.com/danieldestro/cucumber-salad/tree/generics/src/main/java/my/generics

Code can be viewed here: https://github.com/danieldestro/cucumber-salad/tree/generics/src/main/java/my/generics

推荐答案

因为 Step.setConfig(Config) 是"消费者",解决" 不适用于参数(Config) "错误的一种方法是访问

Because Step.setConfig( Config ) is a „consumer", one way to resolve the „is not applicable for the arguments (Config)" error you get is to use a lower bound like I demonstrate here

…  
List< ? extends Config > configs = loadConfigsFromRepository( ); // contain all subtypes of Config
  
for ( Config conf: configs ) {
    Step< ? super Config > step = conf.type( ).getDeclaredConstructor( ).newInstance( );

      step.setConfig( conf ); // *set* makes Step a „consumer"
}
…

这样,您就不需要其他答案提出的强制转换.

That way you don't need the cast that the other answer proposes.

我的 loadConfigsFromRepository() 已实现像

static List< ? extends Config > loadConfigsFromRepository(){ 
    
    return of( new ValidationConf( ), new ProcessConf( ) );        
}

这篇关于如何在泛型和继承中使用方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆