我有一个实用程序类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()
的地方在 OldPojo
和 NewPojo
之间切换。
有什么办法可以解决这个问题吗?
最佳答案
您可以创建一个基类或接口(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/