[英]Same class different package and JAXB
I hace several .xsd and I want to generate classes with JAXB. 我有几个.xsd,我想用JAXB生成类。
Package: v1
Class: JBObject
Class: ...
Package: v2
Class JBObject
Class: ...
I use a factory pattern, if it's v1 I use the classes of v1 and if it's v2 I use the classes of v2. 我使用工厂模式,如果它是v1我使用v1的类,如果它是v2我使用v2的类。 In a version I have to use the classes of package 1 and in other version I have to use the classes of package 2. The classes generated are the same or almost the same. 在一个版本中我必须使用包1的类,而在其他版本中我必须使用包2的类。生成的类是相同或几乎相同的。
I have other class called Translation with the method: 我有其他类称为翻译方法:
import XX.JBObject;
public void translate(JBObject object)
{
...
String name = object.getName();
JBRelationObject relationObject = object.getRelationObject();
int id = relationObject.getId();
...
}
JBObject is the same class in v1 and v2 but I have to import in the class and I don't want to copy and paste twice (one with each import) How can I solve it? JBObject与v1和v2中的类相同但我必须在类中导入,我不想复制和粘贴两次(每次导入一次)我该如何解决?
With import I mean: import v1.JBObject; 使用import我的意思是:import v1.JBObject; or import v2.JBObject; 或导入v2.JBObject;
You have a few options. 你有几个选择。
Option 1: Make both JBObject
classes implement the same interface. 选项1:使两个JBObject
类实现相同的接口。
Since they are generated, you probably can't do that. 由于它们是生成的,您可能无法做到。
Option 2: Wrap them with adapter classes that implement common interface. 选项2:使用实现通用接口的适配器类包装它们。
This is useful if you need shared logic in multiple places. 如果您需要多个位置的共享逻辑,这非常有用。
Option 3: If all your translate()
method needs is JBObject.getName()
, get the name and delegate to common code, eg 选项3:如果所有translate()
方法需要的是JBObject.getName()
,请获取名称并委托公共代码,例如
public void translate(v1.JBObject jb1obj) {
translate(jb1obj.getName());
}
public void translate(v2.JBObject jb2obj) {
translate(jb2obj.getName());
}
private void translate(String name) {
// common logic here
}
No import
statement. 没有import
声明。 Your code handles both versions in a single class. 您的代码处理单个类中的两个版本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.