无法编译类在具有泛型列表参数的接口中调用方法

leh*_*leh 2 java generics

刚刚得到一个关于泛型的问题,为什么在使用泛型List时这不会编译?如果它不可能,反正它周围?非常感谢任何答案.

// Interface used in the ServiceAsync inteface.
public interface BaseObject
{
    public String getId();
}

// Class that implements the interface
public class _ModelDto implements BaseObject, IsSerializable
{
    protected String id;

    public void setId(String id)
    {
        this.id = id;
    }

    public String getId()
    {
        return id;
    }
}

// Interface used in the ServiceAsync inteface.
public interface MyAsync<T>
{
     // Nothing here.
}

// Service interface use both interfaces above.
public interface ServiceAsync
{
    public void getList(MyAsync<List<? extends BaseObject>> callback);
}

public class MyClass
{
    ServiceAsync service = (some implementation);
    MyAsync<List<_ModelDto>> callBack = new MyAsync<List<_ModelDto>>()
    {

    };

    service.getList(callBack);  // This does not compile, says arguments are not applicable????
}
Run Code Online (Sandbox Code Playgroud)

Kri*_*mbe 5

您的MyAsync接口不包含任何方法签名且没有特别信息的名称这一事实从我的角度来看是代码味道,但我认为这只是一个虚拟的例子.在编写时,getList()无法以任何方式使用回调的任何合理实现; 请记住,类型擦除会将此方法签名擦除getList(MyAsync callback);

这不能编译的原因是你的绑定是错误的.MyAsync<List<? extends BaseObject>>给T作为List<? extends BaseObject>一个未知类型的列表.

它看起来像你想要的getList方法本身是通用的:

public interface ServiceAsync {
    public <T extends BaseObject> void getList(MyAsync<List<T>> callback);
}

public class MyClass {
    public void foo() {
        ServiceAsync service = null;
        MyAsync<List<_ModelDto>> callBack = new MyAsync<List<_ModelDto>>() {};

        service.getList (callBack);  // This compiles
    }
}
Run Code Online (Sandbox Code Playgroud)