Java 多级泛型继承

标签 java generics multiple-inheritance restful-architecture

<分区>

我找到的最接近的问题 ( Method Chaining: How to use getThis() trick in case of multi level inheritance ) 没有直接回答我的问题。我目前正在使用吗啡并正在设置休息服务。我已经看过许多版本的如何实现它并决定这样做。然而,我完全愿意接受建议,学习如何解决这个问题,将有助于我的编码实践,至少我认为它会。另外,我知道我的命名约定可能不对,所以我也愿意接受更正 :)

这是我的代码:

                          1st
/*****************************************************************************/
public interface BaseRepository <T extends BaseEntity> {
    /* Methods Here */
}
public class BaseController<T extends BaseEntity> implements BaseRepository<T> {
    public BaseController(Class<T> type) {
         this.type = type;
    }
    /* Overridden Methods Here*/
}
                         2nd
/*****************************************************************************/
public interface UserRepository<T extends UserEntity> extends BaseRepository<UserEntity> {

    /* Methods Here */

}

public class UserController<T extends UserEntity> extends BaseController<UserEntity> implements UserRepository<T> {

    Class<T> type;

    public UserController(Class<T> type) {
        super(type); // <---- Error Here
        this.type = type;
    }

最终,我会想要 StudentController、StaffController 等继承自 UserController。 BaseController 将成为其他 Controller (而非用户)的父级。但是,我不知道解决这个问题的正确方法。我确实尽力满足了

public UserController(Class<T> type) {
        super(type); // <---- Error Here
        this.type = type;
    }

用 UserEntity.class 替换 super(type) 中的“type”,但这只会允许 Basecontroller 返回 UserEntity 属性。任何解决方案?如果有办法......就像我说的那样,我仍在学习并且完全接受其他解决这个问题的建议或关于这个特定问题的任何建议。非常感激!谢谢:)

最佳答案

我想你的意思是

public class UserController<T extends UserEntity> extends BaseController<T> 
                                                  implements UserRepository<T> {

因为这将允许您传递 Class<T>到父类(super class)。

关于Java 多级泛型继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34105032/

相关文章:

java - 在 mule munit 中加载属性

java - 解码扩展抽象泛型类的类

java - 多输入验证整合 Java

c# - 使用泛型处理 C#8 可空引用类型中的不一致行为

c# - 无法理解 "Generics"示例

c# - 是C#编译器还是CLR禁止多重继承

java - Java 8 中多重继承的使用

带有接口(interface)的 Java 编译错误

java - 接口(interface)、抽象和类

java - 为什么我们需要在java文件中使用get方法 @RequestMapping(method = RequestMethod.GET)