覆盖java中的泛型方法

时间:2015-06-04 05:36:16

标签: java generics method-overriding

我在一个抽象类中定义了一个方法,如下所示,

public abstract class AbstractService {
    protected abstract <T> Message<T> executeService(Message<T> msg)
            throws ServiceException;

}

我想在具体的子类中实现此方法,如下所示,

public class RescheduleInfoAdaptor extends AbstractService {
    @Override
    protected Message<RescheduleInfo> executeService(Message<RescheduleInfo> msg)
            throws ServiceException {
        //implementation goes here
    }
}

但是编译器报告错误说

The method executeService(Message<RescheduleInfo>) of type RescheduleInfoAdaptor must override or implement a supertype method

有谁能建议如何在子类中实现所需类型的超类方法?

3 个答案:

答案 0 :(得分:2)

您有两种选择:

要么

  • 将抽象方法类型参数上传到RescheduleInfo(或RescheduleInfo的某些特定超类,类似AbstractInfo

例如:

protected abstract <T extends RescheduleInfo> Message<T> executeService(Message<T> msg)
        throws ServiceException;

但请注意,这将编译,但会生成&#34;类型安全&#34;警告。

  • 使AbstractService泛型并删除抽象方法type-parameter。

例如:

public abstract class AbstractService<T> {
    protected abstract Message<T> executeService(Message<T> msg)
            throws ServiceException;

}

然后,在另一个课程中,您将拥有:

public class RescheduleInfoAdaptor extends AbstractService<RescheduleInfo> {
    @Override
    protected Message<RescheduleInfo> executeService(Message<RescheduleInfo> msg)
            throws ServiceException {
        //implementation goes here
    }
}

答案 1 :(得分:1)

试试这样:

public abstract class AbstractService<T> {
       protected abstract Message<T> executeService(Message<T> msg)

public class RescheduleInfoAdaptor extends AbstractService<RescheduleInfo> {

答案 2 :(得分:1)

您需要更改此

protected abstract <T> Message<T> executeService(Message<T> msg)

到此

protected abstract <T extends Something> Message<T extends Something> executeService(Message<T extends Something> msg)

Where Something是RescheduleInfo

的超类