XML демаршаллинг с использованием JAXB, с типом поля на основе значения атрибута XML? - PullRequest
0 голосов
/ 27 июня 2018

Мое приложение получает из другого приложения xml формы:

<targetedMessage>
    <sender>the sender</sender>
    <payload class="other.app.classpath.Foo">
        <id>1</id>
    </payload>
</targetedMessage>

, где Foo - это любой из нескольких классов, которые существуют как в моем модуле, так и в другом приложении, и реализует общий интерфейс:

@XmlAccessorType(value = XmlAccessType.FIELD)
@XmlRootElement
public class Foo implements MyInterface {
    private long id;
    \\ getters and setters
}

и класс TargetedMessage:

@XmlAccessorType(value = XmlAccessType.FIELD)
@XmlRootElement
public class TargetedMessage {
    private String sender;
    private MyInterface payload;
    \\ getters and setters
}

У меня есть enum, который отображает пути классов других приложений к их классам в моем модуле:

public enum MyClasses {
    FOO(Foo.class, "other.app.classpath.Foo"),
    BAR(Bar.class, "other.app.classpath.Bar"),
    \\ ...
}

Используя JAXB, можно ли разархивировать xml так, чтобы полезные данные имели правильный тип (в приведенном выше случае класс полезных данных будет Foo).

1 Ответ

0 голосов
/ 28 июня 2018

Я не знаю о JAXB, но SimpleXml может это сделать:

@XmlName("targetedMessage")
public class TargetedMessage {
    String sender;
    @XmlAbstactClass(attribute="class", types={
        @TypeMap(name="other.app.classpath.Foo", type=Foo.class),
        @TypeMap(name="other.app.classpath.Bar", type=Bar.class)
    })
    Payload payload;
}
interface Payload {}
public class Foo implements Payload {
    Integer id;
}
public class Bar implements Payload {
    String name;
}

final String data = ...

final SimpleXml simple = new SimpleXml();
final TargetedMessage message = simple.fromXml(data, TargetedMessage.class);
System.out.println(message.payload.getClass().getSimpleName());
System.out.println(((Foo)message.payload).id);

Будет выводить:

Foo
1

Из центральных мавенов:

<dependency>
    <groupId>com.github.codemonstur</groupId>
    <artifactId>simplexml</artifactId>
    <version>1.5.0</version>
</dependency>
...