【问题标题】:Java Multilevel Generic Inheritance [duplicate]Java多级通用继承[重复]
【发布时间】:2016-03-10 08:54:31
【问题描述】:

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

这是我的代码:

                          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 将是其他控制器(不是用户)的父级。但是,我不知道解决此问题的正确方法。我确实试图满足

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

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

【问题讨论】:

    标签: java generics multiple-inheritance restful-architecture


    【解决方案1】:

    我认为你的意图是

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

    因为这将允许您将 Class&lt;T&gt; 传递给超类。

    【讨论】:

    • 我不知道为什么我没有先这样做.... 1 个字符。
    • @MichaelVillar 因为泛型及其错误消息需要一些时间来适应。最初几年,我经常被他们弄糊涂,但那是不久前的事了。 ;)
    • 是的,我对它还是很陌生,感谢您的帮助!谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-11
    • 1970-01-01
    • 2019-03-10
    • 2015-11-11
    • 2014-03-16
    • 2015-01-23
    • 2015-12-24
    相关资源
    最近更新 更多