Java - 具有泛型类型参数的重写方法,并在调用它时对其进行类型转换

标签 java oop overriding generic-type-argument

我有一个实用程序类OldRemote,现在已被弃用,但它仍然会使用一段时间,直到新类NewRemote稳定为止。并且这两个实用程序类具有相同的方法名称和参数,但返回类型pojo类不同。即使返回类型pojo结构相同,但命名不同。

简单来说,两个函数的返回类型都是具有不同字段名称的 pojo。

有没有通用的方法来处理下面的用例?

我创建了一个服务接口(interface),它具有新旧类的通用方法契约。

public interface RemoteService {

    //contract [ return type is object to receive all/any Pojo classes ]
    Object turnOnTV();

    static Service GetRemoteservice(boolean isOldRemote){
        if(isOldRemote){
            return new OldRemote();
        }
        return new NewRemote();
    }
}

OldRemote 类

public class OldRemote implements RemoteService{
    @Override
    public OldPojo turnOnTV() {
        OldPojo oldPojo = new OldPojo();
        System.out.println("OldPojo");
        return oldPojo;
    }
}

新建远程类

public class NewRemote implements Service{
    @Override
    public NewPojo turnOnTV() {
        NewPojo newPojo = new NewPojo();
        System.out.println("NewPojo");
        return newPojo;
    }
}

上述实现的演示用法。

public class DemoTvRemote {
    public static void main(String[] args) {

        RemoteService remoteService1 = RemoteService.GetRemoteservice(true);
        OldPojo oldRemote = (OldPojo) remoteService1.turnOnTV();

        RemoteService remoteService2 = RemoteService.GetRemoteservice(false);
        NewPojo shr = (NewPojo) Service2.test();
    }
}

上面的代码工作正常。但问题是我不想在整个代码库中使用 turnOnTV() 的所有地方都键入强制类型转换。即使我必须这样做,我也必须编写一个条件来在调用 turnOnTV() 的地方在 OldPojoNewPojo 之间切换。

有什么办法可以解决这个问题吗?

最佳答案

您可以创建一个基类或接口(interface),它们都扩展/实现。

public abstract class RemoteServiceBase<E> {
    public abstract E turnOnTv();
}

public class NewRemoteService extends RemoteServiceBase<NewRemotePojo >{
    public NewRemotePojo turnOnTv() {
         return new NewRemotePojo();
    } 
}


public class OldRemoteService extends RemoteServiceBase<OldRemotePojo >{
    public OldRemotePojo turnOnTv() {
         return new OldRemotePojo();
    } 
}

仅当您知道服务类型时,这仍然有效。否则,您将像人们所期望的那样使用常见的泛型类型。

关于Java - 具有泛型类型参数的重写方法,并在调用它时对其进行类型转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55556337/

相关文章:

java - Scala:继承接口(interface)成员初始化

java - 方法重写和重载

java - 当 URL 相同时,如何区分 New relic 中的 GET 和 PUT 请求事务?

c# - oop 检查返回类型是父类还是子类

python - 尝试将 DRY 原则应用于 django 中的建模方法

c# - 如何处理 catch block 中的异常?

java - DefaultTableModel 使单元格不可编辑 JTable

java - 在每个第 i 个和第 j 个字符处拆分

java - 在哪里可以找到并下载 Java Speech API?

java - 使用Bouncy CaSTLe从android中提取证书信息