【问题标题】:How to return extended class like a generic class?如何像泛型类一样返回扩展类?
【发布时间】:2021-07-06 12:11:48
【问题描述】:

我有三个类AdminAccountCustomerAccountConfectionerAccount,它们是从Account 扩展而来的。在 findByUsername(String username) 方法中,我想检查这三个类并返回不为 NULL 的那个。

    public <R extends Account> R findByUsername(String username) {
        AdminAccount adminAccount = adminAccountDao.findByUsername(username).orElse(null);
        CustomerAccount customerAccount = customerAccountDao.findByUsername(username).orElse(null);
        ConfectionerAccount confectionerAccount = confectionerAccountDao.findByUsername(username).orElse(null);
        return Stream.of(adminAccount, customerAccount, confectionerAccount).filter(Objects::nonNull).findFirst().get();
    }

但是当我尝试返回时,我得到了

Required type: R
Provided: Account

请您解释一下,我的错误在哪里?如何返回具体类,如AdminAccountCustomerAccountConfectionerAccount

【问题讨论】:

    标签: java generics inheritance


    【解决方案1】:

    这是对泛型的滥用。泛型类型参数由调用者确定,而不是由被调用者确定,因此findByUsername 无法根据其中哪个帐户为空来确定R 是什么。调用者应该能够决定R 是什么,即我可以做什么:

    class Foo extends Account {}
    
    ...
    
    Foo foo = findByUsername("Sweeper");
    

    你一定可以给我Foo

    显然,findByUsername 无法做到这一点,所以它不应该是通用的。

    您应该在此处返回 Account

    public Account findByUsername(String username) {
    

    现在调用者无法从findByUsername 中选择它想要的帐户类型,这是完全有道理的,因为调用者通常无法“看到”findByUsername 的工作方式以及计算出什么样的帐户它将为给定的用户名返回帐户。

    【讨论】:

      猜你喜欢
      • 2018-07-13
      • 2014-09-08
      • 1970-01-01
      • 2013-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-10
      相关资源
      最近更新 更多