我创建了一个带有通用方法的接口(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/