且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在泛型和继承中使用方法?

更新时间:2023-01-16 08:53:34

因为 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( ) );        
}