[英]How to use constants in XML for XStream
Please, how to define java constant like Integer.MAX_VALUE in XML? 请问,如何在XML中定义类似Integer.MAX_VALUE的java常量? I know how to use enum, but I have third-party library and have to operate with constants. 我知道如何使用枚举,但我有第三方库,必须使用常量操作。 Eg in xml file exists some value and I would like that in generated java class should be declared as constant. 例如在xml文件中存在一些值,我想在生成的java类中应该声明为常量。
XML: XML:
<person>
<firstname>Joe</firstname>
<lastname>Walnes</lastname>
<phone>
<code>123</code>
<number>1234-456</number>
</phone>
<fax>
<code>123</code>
<number>9999-999</number>
</fax>
</person>
Java: Java的:
public class Person {
private String firstname;
private String lastname;
private PhoneNumber phone;
private PhoneNumber fax;
// ... constructors and methods
}
public class PhoneNumber {
private int code;
private String number;
// ... constructors and methods
}
This works. 这有效。 But should be like: 但应该是这样的:
XML: XML:
<person>
<firstname>Joe</firstname>
<lastname>Walnes</lastname>
<phone>
**<const>**PnoneNumber.LOCAL**</const>**
</phone>
<fax>
<code>123</code>
<number>9999-999</number>
</fax>
</person>
Java should be: Java应该是:
public class Person {
private String firstname;
private String lastname;
private PhoneNumber phone;
private PhoneNumber fax;
// ... constructors and methods
}
public class PhoneNumber {
public static final PnoneNumber LOCAL=new PhoneNumber(123,"1234-456");
private int code;
private String number;
// ... constructors and methods
}
Can I do it in easy way and without a custom converter? 我可以轻松地完成这项工作并且没有自定义转换器吗?
Thanks a lot. 非常感谢。
I have looked into several XML-POJO generators, especially those using XML Schema (XSD) to define the classes and to my surprise none offers the ability to modify the attributes. 我已经研究了几个XML-POJO生成器,特别是那些使用XML Schema(XSD)来定义类的生成器,令我惊讶的是,没有提供修改属性的能力。
If you want to keep your current solution I think the cleanest way would be to extend the conversion by your own custom converter, as you said yourself. 如果您想保留当前的解决方案,我认为最简洁的方法是通过您自己的自定义转换器来扩展转换,就像您自己说的那样。
If you use something which makes use of a XML Schema you could always use the attribute fixed="constant"
as standard initialization, though of course it does not preserve the semantics. 如果您使用的是使用XML Schema的东西,您可以始终使用属性fixed="constant"
作为标准初始化,但当然它不会保留语义。
It might be, however, better to resolve this another way. 但是,以另一种方式解决这个问题可能会更好。 These are constants and they ought not to change, so maybe it would be best to define them in a separate file anyway. 这些是常量,它们不应该改变,所以也许最好将它们定义在一个单独的文件中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.