[英]Avoiding instanceof - unmodifiable classes
假设我有两个类A
和B
,使得B extends A
,分别实现了具有相同输入参数类型和相同返回类型(但名称不同)的方法getA
和getB
。 在方法public static <T extends A> void print(T t)
得到作为输入类型的对象A
或B
,我想调用getA
如果对象是类的A
或getB
如果对象是类的B
。
如果可以编辑A
和B
的代码,则可以使它们实现I
提供getValue()
的接口(在A
和B
的实现中, getValue()
调用getA()和getB()),然后调用此方法来自print()
。 问题是: 类A和B不可修改! 。 无法添加或更改任何方法,它们的类层次结构是固定的,我没有编写其代码,也无法访问源代码。
请注意,这也适用于以下情况-由于任何原因-我不想更改A
和B
的代码。
没有使用instanceof
有没有办法做到这一点?
以下是使用instanceof
(坏!)的解决方案。
public class Test {
public static <T extends A> void print(T t){
if (t instanceof B)
System.out.println(((B)t).getB());
else if (t instanceof A)
System.out.println(t.getA());
}
public static class A {
public String getA(){
return "A";
}
}
public static class B extends A {
public String getB(){
return "B";
}
}
}
当由于某种原因而无法访问原始代码时,您最终不得不依靠instanceof之类的东西。 在这些情况下,这本身还不错-双手被绑住了。
我要做的是创建一个在您的T上通用的包装器类,为它提供一个getValue
,以便按照您的建议对instanceof
进行测试,并明确表明该类存在的唯一原因是为使用A或B。它仍然是毛额,但您已将毛额包含在一个位置。
谢谢你和@Matt。 猜猜这绝对是最干净的方法。 将提供不使用instanceof的完整代码:
public static void main(String[] args){
A a = new A();
B b = new B();
AWrapper aw = new AWrapper(a);
BWrapper bw = new BWrapper(b);
print(aw);
print(bw);
}
public static void print(Wrapper t){
System.out.println(t.getValue());
}
public static class A {
public String getA(){
return "A";
}
}
public static class B extends A {
public String getB(){
return "B";
}
}
public static interface Wrapper{
public String getValue();
}
public static class AWrapper implements Wrapper{
A a;
public AWrapper (A a){
this.a = a;
}
public String getValue(){
return a.getA();
}
}
public static class BWrapper implements Wrapper{
B b;
public BWrapper (B b){
this.b = b;
}
public String getValue(){
return b.getB();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.