我有一个使用外部库调用各种网络服务的项目。这个库给了我这样的对象:
public static class ObjA {
@XmlElement(name = "counter", required = true)
protected BigInteger counter;
@XmlElement(name = "data", required = true)
protected String data;
[...]
}
还有这个:
public static class ObjB {
@XmlElement(name = "counter", required = true)
protected BigInteger counter;
@XmlElement(name = "data", required = true)
protected String data;
[...]
}
正如您所看到的 objA 和 objB 具有相同的属性,因此,如果我必须使用两者,我必须重复代码:
public class myClass {
[...]
private ObjA a;
private ObjB b;
[...]
public void myClass() {
[...]
this.a = new ObjectFactory().createObjA();
this.b = new ObjectFactory().createObjB();
[...]
}
public void init() {
this.initA();
this.initB();
}
private void initA() {
this.a.setCounter(BigInteger.ZERO);
this.a.setData = "";
}
private void initB() {
this.b.setCounter(BigInteger.ZERO);
this.b.setData = "";
}
[...]
}
initA 和 initB 是相同的,我无法访问库代码,因此无法创建通用接口(interface),如何避免重复代码?我的意思是,有可能有这样的东西吗?
private void initObj([ObjA|ObjB] obj) {
obj.setCounter(BigInteger.ZERO);
obj.setData = "";
}
谢谢!穆夏斯·格拉西亚斯!
附录
请注意,我无法访问底层库,因此无法以任何方式添加修改类、接口(interface)、wsdl 或 xsd。 另外,在我看来,是否使用 ws、jaxb 或其他库并不重要:您可以想象没有注释的 ObjA 和 ObjB,如下所示:
public static class ObjA {
protected BigInteger counter;
protected String data;
[...]
}
public static class ObjB {
protected BigInteger counter;
protected String data;
[...]
}
问题的关键并没有改变。
最佳答案
我假设这些类是使用某种工具为您生成的,也许是 maven cxf-codegen-plugin 等。 如果是这种情况,您需要修改 WSDL 和 XSD,以便生成令您满意的 DTO 类。 如果 WSDL 已提供给您,那么您只需按原样接受服务即可?
如果你知道公共(public)方法都具有相同的名称,你可以使用反射吗?
所以你可以用原始反射做这样的事情:
import java.lang.reflect.Method;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
public class Test {
public static void initObject(Object o) throws Exception {
if (!(o instanceof ObjA)&&!(o instanceof ObjB)) return;
Method m = o.getClass().getMethod("setCounter",java.math.BigInteger.class);
m.invoke(o,BigInteger.ZERO);
m = o.getClass().getMethod("setData",java.lang.String.class);
m.invoke(o,"");
}
public static void main(final String[] args) throws Exception {
List<Object>objects = new ArrayList<Object>();
//this is like your factory method
Object o = Class.forName("ObjA").newInstance();
initObject(o);
objects.add(o);
o = Class.forName("ObjB").newInstance();
initObject(o);
objects.add(o);
}
}
如果您想使用库,您可以使用 JXPath 和 see docs here 之类的东西。 但我认为对于你的目的来说,原始反射可能就可以了。不需要非常复杂的反射库。
关于Java:相同的对象,如何避免重复的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28459662/