简体   繁体   中英

Same class different package and JAXB

I hace several .xsd and I want to generate classes with 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. 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.

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?

With import I mean: import v1.JBObject; or import v2.JBObject;

You have a few options.

Option 1: Make both JBObject classes implement the same interface.
Since they are generated, you probably can't do that.

Option 2: Wrap them with adapter classes that implement common interface.
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

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. Your code handles both versions in a single class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM