简体   繁体   English

带有WildCard的java中的通用接口

[英]Generic interface in java with WildCard

I am bit confused mixing Java generics interfaces and type wildcard. 我混淆了Java泛型接口和类型通配符。 I am trying to implement a generic way to pass a list of options to a method where the type of the option is unknown at compile type. 我试图实现一种通用的方法来将选项列表传递给一个方法,其中选项的类型在编译类型是未知的。

I did in the following way, but I get an error at compile time. 我用以下方式做了,但是在编译时遇到错误。

Generic Interface : 通用接口:

public interface IOption<T> { 
    public T getOption();
}

This method should take in input a list of options of unknown type, so I used a wild card. 这个方法应该输入一个未知类型的选项列表,所以我用了一张外卡。

public interface IAction {
    boolean do(Iterable<IOption<?>> options);
}

The I created the following list of boolean options : 我创建了以下布尔选项列表:

    IOption<Boolean> option =  new IOption<Boolean>(){
            @Override
            public Boolean getOption() {
                return new Boolean(doEnable);
            }           
        };
    Iterable<IProjectStateOption<Boolean>> options = 
                   Collections.singletonList(option);

but when the method do is called I get the following error : 但是当调用方法do时,我收到以下错误:

The method do( Iterable<IOption<?>>) in the type IAction is not applicable for 
the arguments (Iterable<IOption<Boolean>>)

An Iterable<Option<Boolean>> cannot be converted to an Iterable<Option<?>> , even though Option<Boolean> is convertible to Option<?> . 即使Option<Boolean>可转换为Option<?> Iterable<Option<Boolean>>也无法转换为Iterable<Option<?>>

You want Iterable<? extends Option<?>> 你想要Iterable<? extends Option<?>> Iterable<? extends Option<?>> . Iterable<? extends Option<?>>

You'd have to change your do method or your specific iterator since Iterable<IProjectStateOption> is not valid for Iterable<IOption> . 您必须更改do方法或特定迭代器,因为Iterable<IProjectStateOption>Iterable<IOption>无效。

public interface IAction {
   boolean do(Iterable<? extends IOption> options);
}

If you want to specify the specific type of IOption then you need to to use <T> in IAction as well 如果要指定特定类型的IOption则还需要在IAction使用<T>

public interface IAction<T>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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