简体   繁体   中英

How to use constants in XML for XStream

Please, how to define java constant like Integer.MAX_VALUE in XML? 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:

 <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:

 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:

 <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:

 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.

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.

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.

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