java - 泛型 "method does not override any method from its superclass"

标签 java generics methods interface overriding

我创建了一个带有通用方法的接口(interface),当在实现此接口(interface)的类中重写此方法时,编译器提示说“方法不会重写其父类(super class)中的方法”。仅当我向抽象方法添加通用参数时才会出现此问题。

我创建了一个接口(interface),其中包含一个通用方法和一个实现该接口(interface)的类。

package me.work.rest;
public interface RestControllerFacade<T> {
    <P, R, E extends Throwable> R retrieveCollectionResources(P p) throws E ;
}

@RestController
@RequestMapping("api/v1/Users")
public class UserResource implements RestControllerFacade<User> {
    @GetMapping( produces = MediaType.APPLICATION_JSON_VALUE )
    @Override
    public ResponseEntity<Page<User>> retrieveCollectionResources(Pageable 
    pageable) throws ResourceNotFoundException {
        code...
        return ...;
    }
}

编译器说“方法不会覆盖其父类(super class)中的方法”。 顺便说一句,这段代码对我有用:

package me.work.rest;
public interface RestControllerFacade<T> {
    <R, E extends Throwable> R retrieveCollectionResources() throws E ;
}

@RestController
@RequestMapping("api/v1/Users")
public class UserResource implements RestControllerFacade<User> { 
@GetMapping( produces = MediaType.APPLICATION_JSON_VALUE )
    @Override
    public ResponseEntity<Page<User>> retrieveCollectionResources() throws ResourceNotFoundException {
        code...
        return ...;
    }
}

仅当将 P 参数添加到方法中时,编译器才会提示! 任何帮助表示赞赏。谢谢。

最佳答案

如果您希望它是有效的覆盖,则 P , R ,和E需要是接口(interface)上的泛型,而不是方法上的泛型。必须是

public interface RestControllerFacade<P, R, E extends Exception, T> {
    R retrieveCollectionResources(P p) throws E ;
}

@RestController
@RequestMapping("api/v1/Users")
public class UserResource implements 
        RestControllerFacade<
           Pageable, 
           ResponseEntity<Page<User>>, 
           ResourceNotFoundException, 
           User> {
    @GetMapping( produces = MediaType.APPLICATION_JSON_VALUE )
    @Override
    public ResponseEntity<Page<User>> retrieveCollectionResources(Pageable 
    pageable) throws ResourceNotFoundException {
        code...
        return ...;
    }
}

你写的方式,任何 RestControllerFacade必须能够适用于任何 P , R ,和E ,而不仅仅是一些特定的组合。

关于java - 泛型 "method does not override any method from its superclass",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57032584/

相关文章:

visual-studio - Visual Studio 重构 : Remove method

java - 第一个 JSP 页面 — 使用 2D 数组 — 页面未填充

java - 列索引超出范围 : 2, 第 1 列的编号

java - JDT : Nesting MethodInvocation

ios - 如何创建接受泛型类型作为关联类型的枚举

java - if else 语句没有停止问题

java - WebSphere REST 服务错误 "FFDC Incident emitted"

c# - 生成引用自身的类

Swift 创建函数闭包,支持缩短的美元符号语法

java - 列出 Java 中 Groovy 类的已声明方法