0

I am using multiple XStream instances in a same class.

Is the below implementation of an XStream factory thread-safe, and are there any significant performance implications?

public final class XStreamFactory {

    private XStreamFactory() {
    }

    public static XStream getXstream(Class<?> clazz) {
        XStream xstream = new XStream() {
            @Override
            protected MapperWrapper wrapMapper(MapperWrapper next) {
                return new MapperWrapper(next) {
                    @Override
                    public boolean shouldSerializeMember(@SuppressWarnings("rawtypes") Class definedIn, String fieldName) {
                        if (definedIn == Object.class)
                            return false;

                        return super.shouldSerializeMember(definedIn, fieldName);
                    }
                };
            }
        };

        if (clazz != null) {
            xstream.autodetectAnnotations(Boolean.TRUE);
            xstream.processAnnotations(clazz);
        }

        return xstream;
    }
}

Converting XML to Java

Public class Resposne {

    private XStream xstream1=XStreamFactory.getXstream(XClass1.class);
    private XStream xstream2=XStreamFactory.getXstream(XClass2.class);

    public XClass1 readReplyOne(String reply1){
        return (XClass1) xstream1.fromXML(reply1)
    }

    public XClass2 readReplyOne(String reply2){
        return (XClass2) xstream2.fromXML(reply2)
    }
}
nbrooks
  • 18,126
  • 5
  • 54
  • 66
Patan
  • 17,073
  • 36
  • 124
  • 198
  • using 2 instances should be OK performance wise. Note that in your case you could use one instance (using `xstream.processAnnotations(XClass1.class);xstream.processAnnotations(XClass2.class);` directly) –  Oct 27 '16 at 05:35
  • @RC. Thank you. I had tried to using process annotations. But as the Xml root element is same I got errors. http://stackoverflow.com/questions/40263289/xstream-xml-to-java-fails-with-classcast-exception/40263523?noredirect=1#comment67788246_40263523 – Patan Oct 27 '16 at 05:47
  • IMHO, you are going along the wrong road, how about using some `Reply` class with two fields `status` and `message`, that would probably make your life easier, no? –  Oct 27 '16 at 13:11
  • @RC.yes you true. I will try that. Thank you – Patan Oct 27 '16 at 14:31

0 Answers0