Java泛型方法重写 [英] Java generics method overriding

查看:674
本文介绍了Java泛型方法重写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有接口:

I have interface:

public interface CartService extends RemoteService{
    <T extends ActionResponse> T execute(Action<T> action);
}

我希望覆盖执行中的'execute'方法:

I wish override 'execute' method in implementation:

public class XX implements CartService {

  @Override
  public <GetCartResponse> GetCartResponse execute(GetCart action) {
    // TODO Auto-generated method stub
    return null;
  }
}

但接收编译器错误:
方法XX类型的执行(GetCart)必须覆盖或实现一个超类型方法

But receive compiler error: The method execute(GetCart) of type XX must override or implement a supertype method

GetCart& GetCartResponse:

GetCart & GetCartResponse:

public class GetCart implements Action<GetCartResponse>{

}


public class GetCartResponse implements ActionResponse {
    private final ArrayList<CartItemRow> items;

    public GetCartResponse(ArrayList<CartItemRow> items) {
        this.items = items;
    }

    public ArrayList<CartItemRow> getItems() {
        return items;
    }

}

如何覆盖此方法?

推荐答案

问题在于接口的定义与erausre应该为您的impl应该是什么样子。在你的例子中你有:

The problem is the definition of the interface vs what the erausre should look like for your impl. In your example you have:

<T extends ActionResponse> T execute(Action<T> action);
public <GetCartResponse> GetCartResponse execute(GetCart action);

但根据界面定义,实现方法应为:

but according to the interface definition the implementation method should read:

public GetCartResponse execute(Action<GetCartResponse> action);

所以我认为您需要更改界面的签名或添加其他类型参数,例如:

So I think you either need to change the signature of your interface or add another type parameter such as:

public interface CartService extends RemoteService{
    <T extends ActionResponse, U extends Action> T execute(U action);
}

或者可能与以下内容类似:

or possibly something along the lines of:

public interface CartService extends RemoteService{
    <T extends ActionItem> ActionResponse<T> execute(Action<T> action);
}

这篇关于Java泛型方法重写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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