Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XStream - how to throw an exception if an annotated field is not present in XML

I have something like this:

Java Class

.....
@XStreamAlias("SOME_TAG")
    private String someAttribute;
.....

<ROOT>
    <ANOTHER_TAG>VALUE</ANOTHER_TAG>
</ROOT>

And in my xml i need to have this "SOME_TAG", if for some reason it is missing i need to throw an exception.

Can i do it with XStream?

Regards

like image 837
John Avatar asked Feb 03 '26 01:02

John


2 Answers

I'm not a experimented user of xstream, but I would do this:

  1. Make a dtd file or xsd file, where you can specify the required elements, then you can validate the xml file against the dtd or xsd file. Or,
  2. Make a validation method inside the class for validate is any field is null or any other validation you need to do.
like image 147
nashuald Avatar answered Feb 04 '26 14:02

nashuald


Purely using XStream I think you have two options:

  1. XStream uses the same mechanism as the JDK serialization, so you can simply implement a Object readResolve() method in your class that is being deserialized. This method is called after the object has been initialized and had all fields set by XStream, so you can use this method to check if your someAttribute field is null - if it is you can then throw an exception. (Examples from XStream can be found here: http://x-stream.github.io/faq.html#Serialization_initialize_transient

  2. Another alternative would be to write a custom Converter for your class and check there if the field is filled or not.

like image 45
DB5 Avatar answered Feb 04 '26 15:02

DB5