Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/design-patterns/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Design patterns 好的JAXB设计模式来包装模型和/或转换模型(POJO)?_Design Patterns_Jaxb - Fatal编程技术网

Design patterns 好的JAXB设计模式来包装模型和/或转换模型(POJO)?

Design patterns 好的JAXB设计模式来包装模型和/或转换模型(POJO)?,design-patterns,jaxb,Design Patterns,Jaxb,我有下面的型号 class MyClass { id someRandomString } 我想把这个POJO作为 <Root> <random>if + randomstring</random> </Root> 所以JAXB将只映射getRandom 我的另一个想法是创建一组表示最终输出的类,并将值设置为thoses 所以 然后我可以做 myResponse.setRandomString(myClass.getId

我有下面的型号

class MyClass {
    id
    someRandomString
}
我想把这个POJO作为

<Root>
    <random>if + randomstring</random>
</Root>
所以JAXB将只映射getRandom

我的另一个想法是创建一组表示最终输出的类,并将值设置为thoses

所以

然后我可以做

myResponse.setRandomString(myClass.getId() + myClass.getSomeRandomString());

可以结合使用,但我认为可能需要将id和someRandomString属性封装到单独的类中。如果可能的话,我不知道如何将元素值直接分布在两个单独的bean属性上。

您可以使用
id
someRandomString
字段来分离元素,并使用样式表将元素组合成一个。JAXB提供了与
javax.xml.transform
API相匹配的
JAXBSource
类:

MyClass myClass = new MyClass();
myClass.setId(123);
myClass.setSomeRandomString("FOO");

TransformerFactory tf = TransformerFactory.newInstance();
StreamSource xslt = new StreamSource(new FileInputStream("my-xslt.xml"));
Transformer t = tf.newTransformer(xslt);

JAXBContext jc = JAXBContext.newInstance(MyClass.class);
JAXBSource source = new JAXBSource(jc, myClass);

StreamResult result = new StreamResult(System.out);

t.transform(source, result);

如果我在进行合并的pojo中添加了一个get,并且只将该getter映射到XML输出,会怎么样?您需要一个getter和setter来允许编组和解编组,但这实际上是一个非常好的主意。让一些getter/setter与一个从未使用过的对应字段配对(以确保它被识别为bean属性),并将逻辑放入其中以填充两个实际的目标字段,如一些诱饵和开关。它有点黑,但它可以工作!
class MyResponse {
    randomString
    status
    someOtherFieldRequired in response
}    
myResponse.setRandomString(myClass.getId() + myClass.getSomeRandomString());
MyClass myClass = new MyClass();
myClass.setId(123);
myClass.setSomeRandomString("FOO");

TransformerFactory tf = TransformerFactory.newInstance();
StreamSource xslt = new StreamSource(new FileInputStream("my-xslt.xml"));
Transformer t = tf.newTransformer(xslt);

JAXBContext jc = JAXBContext.newInstance(MyClass.class);
JAXBSource source = new JAXBSource(jc, myClass);

StreamResult result = new StreamResult(System.out);

t.transform(source, result);