简体   繁体   English

在Java中传递通配符通用数据类型的通用

[英]Pass generic of wildcard generic data type in java

I have this classes: 我有这个课程:

public interface DataAccessor<E extends Model, U>

public class Data<T> implements DataMenuItemObservable<T> {

this interface: 该接口:

interface Listener<T> {
    void onResponse(T value);
}

this methods: 此方法:

public interface DataAccessor<E extends Model, U> extends DataMenuItemObservable<E> {

...

    public DataAccessor<? extends Model, ?> getPrimaryDataAccessor()

    void get(int index, Context context, Listener<Data<E>> listener, ErrorListener errorListener);

...

}

and get compiler error on this code: 并获得此代码的编译器错误:

DataAccessor<? extends Model, ?> accessor = db.getPrimaryDataAccessor();
accessor.get(0, this, new DataAccessor.Listener<Data<? extends Model>>() {
            @Override
            public void onResponse(Data<? extends Model> value) {
            }
        }, this);

idea says incompatible types: <anonimous Listener<Data<? extends Model>>> cannot be converted to Listener<Data<CAP#1>> 想法说不incompatible types: <anonimous Listener<Data<? extends Model>>> cannot be converted to Listener<Data<CAP#1>> incompatible types: <anonimous Listener<Data<? extends Model>>> cannot be converted to Listener<Data<CAP#1>>

I also tried implementing interface with this but same error. 我也尝试用this但同样的错误实现接口。

How to fix error ? 如何解决错误? Is there some acceptable workaround ? 有一些可接受的解决方法吗?

The reason it doesn't work is because the compiler doesn't know whether the two wildcards ( ? extends Model ) actually refer to the same type. 它不起作用的原因是因为编译器不知道两个通配符( ? extends Model )是否实际上引用了相同的类型。 You can work around this by creating a helper method to capture the type: 您可以通过创建一个辅助方法来捕获类型来解决此问题:

private <E extends Model> void get(DataAccessor<E, ?> accessor);
    accessor.get(0, this, new DataAccessor.Listener<Data<E>>() {
        @Override
        public void onResponse(Data<E> value) {
            //...
        }
    }, this);
}

Now call the helper: 现在致电助手:

DataAccessor<? extends Model, ?> accessor = db.getPrimaryDataAccessor();
get(accessor);

Shmosel has a good solution. Shmosel有一个很好的解决方案。 I just want to add that, if you have Java 8, you can use a lambda which can infer the right type, contrary to an anonymous class: 我只想补充一点,如果您有Java 8,则可以使用可以推断正确类型的lambda,这与匿名类相反:

DataAccessor<? extends Model, ?> accessor = db.getPrimaryDataAccessor();
accessor.get(0, this, value -> {
        // code
    }, this);

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

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