XStream方法列表

http://xstream.codehaus.org/javadoc/com/thoughtworks/xstream/XStream.html#ignoreUnknownElements%28%29

com.thoughtworks.xstream

Class XStream



  • public class XStream
    extends Object
    Simple facade to XStream library, a Java-XML serialization tool.
    Example
     XStream xstream = new XStream();
     String xml = xstream.toXML(myObject); // serialize to XML
     Object myObject2 = xstream.fromXML(xml); // deserialize from XML
     

    Aliasing classes

    To create shorter XML, you can specify aliases for classes using the alias() method. For example, you can shorten all occurrences of element <com.blah.MyThing> to <my-thing> by registering an alias for the class.


     xstream.alias("my-thing", MyThing.class);
     

    Converters

    XStream contains a map of Converter instances, each of which acts as a strategy for converting a particular type of class to XML and back again. Out of the box, XStream contains converters for most basic types (String, Date, int, boolean, etc) and collections (Map, List, Set, Properties, etc). For other objects reflection is used to serialize each field recursively.

    Extra converters can be registered using the registerConverter() method. Some non-standard converters are supplied in the com.thoughtworks.xstream.converters.extended package and you can create your own by implementing the Converter interface.


    Example
     xstream.registerConverter(new SqlTimestampConverter());
     xstream.registerConverter(new DynamicProxyConverter());
     

    The converters can be registered with an explicit priority. By default they are registered with XStream.PRIORITY_NORMAL. Converters of same priority will be used in the reverse sequence they have been registered. The default converter, i.e. the converter which will be used if no other registered converter is suitable, can be registered with priority XStream.PRIORITY_VERY_LOW. XStream uses by default the ReflectionConverter as the fallback converter.


    Example
     xstream.registerConverter(new CustomDefaultConverter(), XStream.PRIORITY_VERY_LOW);
     

    Object graphs

    XStream has support for object graphs; a deserialized object graph will keep references intact, including circular references.

    XStream can signify references in XML using either relative/absolute XPath or IDs. The mode can be changed using setMode():

     
    xstream.setMode(XStream.XPATH_RELATIVE_REFERENCES); (Default) Uses XPath relative references to signify duplicate references. This produces XML with the least clutter.
    xstream.setMode(XStream.XPATH_ABSOLUTE_REFERENCES); Uses XPath absolute references to signify duplicate references. This produces XML with the least clutter.
    xstream.setMode(XStream.SINGLE_NODE_XPATH_RELATIVE_REFERENCES); Uses XPath relative references to signify duplicate references. The XPath expression ensures that a single node only is selected always.
    xstream.setMode(XStream.SINGLE_NODE_XPATH_ABSOLUTE_REFERENCES); Uses XPath absolute references to signify duplicate references. The XPath expression ensures that a single node only is selected always.
    xstream.setMode(XStream.ID_REFERENCES); Uses ID references to signify duplicate references. In some scenarios, such as when using hand-written XML, this is easier to work with.
    xstream.setMode(XStream.NO_REFERENCES); This disables object graph support and treats the object structure like a tree. Duplicate references are treated as two separate objects and circular references cause an exception. This is slightly faster and uses less memory than the other two modes.

    Thread safety

    The XStream instance is thread-safe. That is, once the XStream instance has been created and configured, it may be shared across multiple threads allowing objects to be serialized/deserialized concurrently. Note, that this only applies if annotations are not auto-detected on-the-fly.

    Implicit collections

    To avoid the need for special tags for collections, you can define implicit collections using one of the addImplicitCollection methods.

    Author:
    Joe Walnes, Jörg Schaible, Mauro Talevi, Guilherme Silveira
    • Method Detail

      • useXStream11XmlFriendlyMapper

        protected boolean useXStream11XmlFriendlyMapper()
        Deprecated.  As of 1.4.8
      • setupSecurity

        protected void setupSecurity()
      • setupAliases

        protected void setupAliases()
      • setupDefaultImplementations

        protected void setupDefaultImplementations()
      • setupConverters

        protected void setupConverters()
      • setupImmutableTypes

        protected void setupImmutableTypes()
      • setMarshallingStrategy

        public void setMarshallingStrategy(MarshallingStrategy marshallingStrategy)
      • toXML

        public String toXML(Object obj)
        Serialize an object to a pretty-printed XML String.
        Throws:
        XStreamException - if the object cannot be serialized
      • toXML

        public void toXML(Object obj,
                          Writer out)
        Serialize an object to the given Writer as pretty-printed XML. The Writer will be flushed afterwards and in case of an exception.
        Throws:
        XStreamException - if the object cannot be serialized
      • toXML

        public void toXML(Object obj,
                          OutputStream out)
        Serialize an object to the given OutputStream as pretty-printed XML. The OutputStream will be flushed afterwards and in case of an exception.
        Throws:
        XStreamException - if the object cannot be serialized
      • marshal

        public void marshal(Object obj,
                            HierarchicalStreamWriter writer,
                            DataHolder dataHolder)
        Serialize and object to a hierarchical data structure (such as XML).
        Parameters:
        dataHolder - Extra data you can use to pass to your converters. Use this as you want. If not present, XStream shall create one lazily as needed.
        Throws:
        XStreamException - if the object cannot be serialized
      • fromXML

        public Object fromXML(String xml)
        Deserialize an object from an XML String.
        Throws:
        XStreamException - if the object cannot be deserialized
      • fromXML

        public Object fromXML(Reader reader)
        Deserialize an object from an XML Reader.
        Throws:
        XStreamException - if the object cannot be deserialized
      • fromXML

        public Object fromXML(URL url)
        Deserialize an object from a URL. Depending on the parser implementation, some might take the file path as SystemId to resolve additional references.
        Throws:
        XStreamException - if the object cannot be deserialized
        Since:
        1.4
      • fromXML

        public Object fromXML(File file)
        Deserialize an object from a file. Depending on the parser implementation, some might take the file path as SystemId to resolve additional references.
        Throws:
        XStreamException - if the object cannot be deserialized
        Since:
        1.4
      • fromXML

        public Object fromXML(String xml,
                              Object root)
        Deserialize an object from an XML String, populating the fields of the given root object instead of instantiating a new one. Note, that this is a special use case! With the ReflectionConverter XStream will write directly into the raw memory area of the existing object. Use with care!
        Throws:
        XStreamException - if the object cannot be deserialized
      • fromXML

        public Object fromXML(Reader xml,
                              Object root)
        Deserialize an object from an XML Reader, populating the fields of the given root object instead of instantiating a new one. Note, that this is a special use case! With the ReflectionConverter XStream will write directly into the raw memory area of the existing object. Use with care!
        Throws:
        XStreamException - if the object cannot be deserialized
      • fromXML

        public Object fromXML(URL url,
                              Object root)
        Deserialize an object from a URL, populating the fields of the given root object instead of instantiating a new one. Note, that this is a special use case! With the ReflectionConverter XStream will write directly into the raw memory area of the existing object. Use with care! Depending on the parser implementation, some might take the file path as SystemId to resolve additional references.
        Throws:
        XStreamException - if the object cannot be deserialized
        Since:
        1.4
      • fromXML

        public Object fromXML(File file,
                              Object root)
        Deserialize an object from a file, populating the fields of the given root object instead of instantiating a new one. Note, that this is a special use case! With the ReflectionConverter XStream will write directly into the raw memory area of the existing object. Use with care! Depending on the parser implementation, some might take the file path as SystemId to resolve additional references.
        Throws:
        XStreamException - if the object cannot be deserialized
        Since:
        1.4
      • fromXML

        public Object fromXML(InputStream input,
                              Object root)
        Deserialize an object from an XML InputStream, populating the fields of the given root object instead of instantiating a new one. Note, that this is a special use case! With the ReflectionConverter XStream will write directly into the raw memory area of the existing object. Use with care!
        Throws:
        XStreamException - if the object cannot be deserialized
      • unmarshal

        public Object unmarshal(HierarchicalStreamReader reader,
                                Object root)
        Deserialize an object from a hierarchical data structure (such as XML), populating the fields of the given root object instead of instantiating a new one. Note, that this is a special use case! With the ReflectionConverter XStream will write directly into the raw memory area of the existing object. Use with care!
        Throws:
        XStreamException - if the object cannot be deserialized
      • unmarshal

        public Object unmarshal(HierarchicalStreamReader reader,
                                Object root,
                                DataHolder dataHolder)
        Deserialize an object from a hierarchical data structure (such as XML).
        Parameters:
        root - If present, the passed in object will have its fields populated, as opposed to XStream creating a new instance. Note, that this is a special use case! With the ReflectionConverter XStream will write directly into the raw memory area of the existing object. Use with care!
        dataHolder - Extra data you can use to pass to your converters. Use this as you want. If not present, XStream shall create one lazily as needed.
        Throws:
        XStreamException - if the object cannot be deserialized
      • aliasType

        public void aliasType(String name,
                              Class type)
        Alias a type to a shorter name to be used in XML elements. Any class that is assignable to this type will be aliased to the same name.
        Parameters:
        name - Short name
        type - Type to be aliased
        Throws:
        XStream.InitializationException - if no ClassAliasingMapper is available
        Since:
        1.2
      • aliasSystemAttribute

        public void aliasSystemAttribute(String alias,
                                         String systemAttributeName)
        Create an alias for a system attribute. XStream will not write a system attribute if its alias is set to null. However, this is not reversible, i.e. deserialization of the result is likely to fail afterwards and will not produce an object equal to the originally written one.
        Parameters:
        alias - the alias itself (may be null)
        systemAttributeName - the name of the system attribute
        Throws:
        XStream.InitializationException - if no SystemAttributeAliasingMapper is available
        Since:
        1.3.1
      • aliasAttribute

        public void aliasAttribute(Class definedIn,
                                   String attributeName,
                                   String alias)
        Create an alias for an attribute.
        Parameters:
        definedIn - the type where the attribute is defined
        attributeName - the name of the attribute
        alias - the alias itself
        Throws:
        XStream.InitializationException - if no AttributeAliasingMapper is available
        Since:
        1.2.2
      • useAttributeFor

        public void useAttributeFor(String fieldName,
                                    Class type)
        Use an attribute for a field or a specific type.
        Parameters:
        fieldName - the name of the field
        type - the Class of the type to be rendered as XML attribute
        Throws:
        XStream.InitializationException - if no AttributeMapper is available
        Since:
        1.2
      • useAttributeFor

        public void useAttributeFor(Class definedIn,
                                    String fieldName)
        Use an attribute for a field declared in a specific type.
        Parameters:
        fieldName - the name of the field
        definedIn - the Class containing such field
        Throws:
        XStream.InitializationException - if no AttributeMapper is available
        Since:
        1.2.2
      • useAttributeFor

        public void useAttributeFor(Class type)
        Use an attribute for an arbitrary type.
        Parameters:
        type - the Class of the type to be rendered as XML attribute
        Throws:
        XStream.InitializationException - if no AttributeMapper is available
        Since:
        1.2
      • addDefaultImplementation

        public void addDefaultImplementation(Class defaultImplementation,
                                             Class ofType)
        Associate a default implementation of a class with an object. Whenever XStream encounters an instance of this type, it will use the default implementation instead. For example, java.util.ArrayList is the default implementation of java.util.List.
        Parameters:
        defaultImplementation -
        ofType -
        Throws:
        XStream.InitializationException - if no DefaultImplementationsMapper is available
      • addImmutableType

        public void addImmutableType(Class type)
        Add immutable types. The value of the instances of these types will always be written into the stream even if they appear multiple times.
        Throws:
        XStream.InitializationException - if no ImmutableTypesMapper is available
      • registerConverter

        public void registerConverter(Converter converter)
      • registerConverter

        public void registerConverter(Converter converter,
                                      int priority)
      • registerLocalConverter

        public void registerLocalConverter(Class definedIn,
                                           String fieldName,
                                           Converter converter)
        Register a local Converter for a field.
        Parameters:
        definedIn - the class type the field is defined in
        fieldName - the field name
        converter - the converter to use
        Since:
        1.3
      • registerLocalConverter

        public void registerLocalConverter(Class definedIn,
                                           String fieldName,
                                           SingleValueConverter converter)
        Register a local SingleValueConverter for a field.
        Parameters:
        definedIn - the class type the field is defined in
        fieldName - the field name
        converter - the converter to use
        Since:
        1.3
      • getMapper

        public Mapper getMapper()
        Retrieve the Mapper. This is by default a chain of MapperWrappers.
        Returns:
        the mapper
        Since:
        1.2
      • addImplicitCollection

        public void addImplicitCollection(Class ownerType,
                                          String fieldName)
        Adds a default implicit collection which is used for any unmapped XML tag.
        Parameters:
        ownerType - class owning the implicit collection
        fieldName - name of the field in the ownerType. This field must be a concrete collection type or matching the default implementation type of the collection type.
      • addImplicitCollection

        public void addImplicitCollection(Class ownerType,
                                          String fieldName,
                                          Class itemType)
        Adds implicit collection which is used for all items of the given itemType.
        Parameters:
        ownerType - class owning the implicit collection
        fieldName - name of the field in the ownerType. This field must be a concrete collection type or matching the default implementation type of the collection type.
        itemType - type of the items to be part of this collection
        Throws:
        XStream.InitializationException - if no ImplicitCollectionMapper is available
      • addImplicitCollection

        public void addImplicitCollection(Class ownerType,
                                          String fieldName,
                                          String itemFieldName,
                                          Class itemType)
        Adds implicit collection which is used for all items of the given element name defined by itemFieldName.
        Parameters:
        ownerType - class owning the implicit collection
        fieldName - name of the field in the ownerType. This field must be a concrete collection type or matching the default implementation type of the collection type.
        itemFieldName - element name of the implicit collection
        itemType - item type to be aliases be the itemFieldName
        Throws:
        XStream.InitializationException - if no ImplicitCollectionMapper is available
      • addImplicitArray

        public void addImplicitArray(Class ownerType,
                                     String fieldName)
        Adds an implicit array.
        Parameters:
        ownerType - class owning the implicit array
        fieldName - name of the array field
        Since:
        1.4
      • addImplicitArray

        public void addImplicitArray(Class ownerType,
                                     String fieldName,
                                     Class itemType)
        Adds an implicit array which is used for all items of the given itemType when the array type matches.
        Parameters:
        ownerType - class owning the implicit array
        fieldName - name of the array field in the ownerType
        itemType - type of the items to be part of this array
        Throws:
        XStream.InitializationException - if no ImplicitCollectionMapper is available or the array type does not match the itemType
        Since:
        1.4
      • addImplicitArray

        public void addImplicitArray(Class ownerType,
                                     String fieldName,
                                     String itemName)
        Adds an implicit array which is used for all items of the given element name defined by itemName.
        Parameters:
        ownerType - class owning the implicit array
        fieldName - name of the array field in the ownerType
        itemName - alias name of the items
        Throws:
        XStream.InitializationException - if no ImplicitCollectionMapper is available
        Since:
        1.4
      • addImplicitMap

        public void addImplicitMap(Class ownerType,
                                   String fieldName,
                                   Class itemType,
                                   String keyFieldName)
        Adds an implicit map.
        Parameters:
        ownerType - class owning the implicit map
        fieldName - name of the field in the ownerType. This field must be a concrete map type or matching the default implementation type of the map type.
        itemType - type of the items to be part of this map as value
        keyFieldName - the name of the field of the itemType that is used for the key in the map
        Since:
        1.4
      • addImplicitMap

        public void addImplicitMap(Class ownerType,
                                   String fieldName,
                                   String itemName,
                                   Class itemType,
                                   String keyFieldName)
        Adds an implicit map.
        Parameters:
        ownerType - class owning the implicit map
        fieldName - name of the field in the ownerType. This field must be a concrete map type or matching the default implementation type of the map type.
        itemName - alias name of the items
        itemType - type of the items to be part of this map as value
        keyFieldName - the name of the field of the itemType that is used for the key in the map
        Since:
        1.4
      • createObjectOutputStream

        public ObjectOutputStream createObjectOutputStream(HierarchicalStreamWriter writer,
                                                           String rootNodeName)
                                                    throws IOException
        Creates an ObjectOutputStream that serializes a stream of objects to the writer using XStream.

        Because an ObjectOutputStream can contain multiple items and XML only allows a single root node, the stream must be written inside an enclosing node.

        It is necessary to call ObjectOutputStream.close() when done, otherwise the stream will be incomplete.

        Example

          ObjectOutputStream out = xstream.createObjectOutputStream(aWriter, "things");
           out.writeInt(123);
           out.writeObject("Hello");
           out.writeObject(someObject)
           out.close();
         
        Parameters:
        writer - The writer to serialize the objects to.
        rootNodeName - The name of the root node enclosing the stream of objects.
        Throws:
        IOException
        Since:
        1.0.3
        See Also:
        createObjectInputStream(com.thoughtworks.xstream.io.HierarchicalStreamReader)
      • setClassLoader

        public void setClassLoader(ClassLoader classLoader)
        Change the ClassLoader XStream uses to load classes. Creating an XStream instance it will register for all kind of classes and types of the current JDK, but not for any 3rd party type. To ensure that all other types are loaded with your class loader, you should call this method as early as possible - or consider to provide the class loader directly in the constructor.
        Since:
        1.1.1
      • getClassLoader

        public ClassLoader getClassLoader()
        Retrieve the ClassLoader XStream uses to load classes.
        Since:
        1.1.1
      • getClassLoaderReference

        public ClassLoaderReference getClassLoaderReference()
        Retrieve the reference to this instance' ClassLoader. Use this reference for other XStream components (like converters) to ensure that they will use a changed ClassLoader instance automatically.
        Returns:
        the reference
        Since:
        1.4.5
      • omitField

        public void omitField(Class definedIn,
                              String fieldName)
        Prevents a field from being serialized. To omit a field you must always provide the declaring type and not necessarily the type that is converted.
        Throws:
        XStream.InitializationException - if no FieldAliasingMapper is available
        Since:
        1.1.3
      • ignoreUnknownElements

        public void ignoreUnknownElements()
        Ignore all unknown elements.
        Since:
        1.4.5
      • ignoreUnknownElements

        public void ignoreUnknownElements(String pattern)
        Add pattern for unknown element names to ignore.
        Parameters:
        pattern - the name pattern as regular expression
        Since:
        1.4.5
      • ignoreUnknownElements

        public void ignoreUnknownElements(Pattern pattern)
        Add pattern for unknown element names to ignore.
        Parameters:
        pattern - the name pattern as regular expression
        Since:
        1.4.5
      • processAnnotations

        public void processAnnotations(Class[] types)
        Process the annotations of the given types and configure the XStream.
        Parameters:
        types - the types with XStream annotations
        Since:
        1.3
      • processAnnotations

        public void processAnnotations(Class type)
        Process the annotations of the given type and configure the XStream. A call of this method will automatically turn the auto-detection mode for annotations off.
        Parameters:
        type - the type with XStream annotations
        Since:
        1.3
      • autodetectAnnotations

        public void autodetectAnnotations(boolean mode)
        Set the auto-detection mode of the AnnotationMapper. Note that auto-detection implies that the XStream is configured while it is processing the XML steams. This is a potential concurrency problem. Also is it technically not possible to detect all class aliases at deserialization. You have been warned!
        Parameters:
        mode - true if annotations are auto-detected
        Since:
        1.3
      • addPermission

        public void addPermission(TypePermission permission)
        Add a new security permission.

        Permissions are evaluated in the added sequence. An instance of NoTypePermission or AnyTypePermission will implicitly wipe any existing permission.

        Parameters:
        permission - the permission to add
        Since:
        1.4.7
      • allowTypes

        public void allowTypes(String[] names)
        Add security permission for explicit types by name.
        Parameters:
        names - the type names to allow
        Since:
        1.4.7
      • allowTypes

        public void allowTypes(Class[] types)
        Add security permission for explicit types.
        Parameters:
        types - the types to allow
        Since:
        1.4.7
      • allowTypeHierarchy

        public void allowTypeHierarchy(Class type)
        Add security permission for a type hierarchy.
        Parameters:
        type - the base type to allow
        Since:
        1.4.7
      • allowTypesByRegExp

        public void allowTypesByRegExp(String[] regexps)
        Add security permission for types matching one of the specified regular expressions.
        Parameters:
        regexps - the regular expressions to allow type names
        Since:
        1.4.7
      • allowTypesByRegExp

        public void allowTypesByRegExp(Pattern[] regexps)
        Add security permission for types matching one of the specified regular expressions.
        Parameters:
        regexps - the regular expressions to allow type names
        Since:
        1.4.7
      • allowTypesByWildcard

        public void allowTypesByWildcard(String[] patterns)
        Add security permission for types matching one of the specified wildcard patterns.

        Supported are patterns with path expressions using dot as separator:

        • ?: one non-control character except separator, e.g. for 'java.net.Inet?Address'
        • *: arbitrary number of non-control characters except separator, e.g. for types in a package like 'java.lang.*'
        • **: arbitrary number of non-control characters including separator, e.g. for types in a package and subpackages like 'java.lang.**'
        Parameters:
        patterns - the patterns to allow type names
        Since:
        1.4.7
      • denyPermission

        public void denyPermission(TypePermission permission)
        Add security permission denying another one.
        Parameters:
        permission - the permission to deny
        Since:
        1.4.7
      • denyTypes

        public void denyTypes(String[] names)
        Add security permission forbidding explicit types by name.
        Parameters:
        names - the type names to forbid
        Since:
        1.4.7
      • denyTypes

        public void denyTypes(Class[] types)
        Add security permission forbidding explicit types.
        Parameters:
        types - the types to forbid
        Since:
        1.4.7
      • denyTypeHierarchy

        public void denyTypeHierarchy(Class type)
        Add security permission forbidding a type hierarchy.
        Parameters:
        type - the base type to forbid
        Since:
        1.4.7
      • denyTypesByRegExp

        public void denyTypesByRegExp(String[] regexps)
        Add security permission forbidding types matching one of the specified regular expressions.
        Parameters:
        regexps - the regular expressions to forbid type names
        Since:
        1.4.7
      • denyTypesByRegExp

        public void denyTypesByRegExp(Pattern[] regexps)
        Add security permission forbidding types matching one of the specified regular expressions.
        Parameters:
        regexps - the regular expressions to forbid type names
        Since:
        1.4.7
      • denyTypesByWildcard

        public void denyTypesByWildcard(String[] patterns)
        Add security permission forbidding types matching one of the specified wildcard patterns.

        Supported are patterns with path expressions using dot as separator:

        • ?: one non-control character except separator, e.g. for 'java.net.Inet?Address'
        • *: arbitrary number of non-control characters except separator, e.g. for types in a package like 'java.lang.*'
        • **: arbitrary number of non-control characters including separator, e.g. for types in a package and subpackages like 'java.lang.**'
        Parameters:
        patterns - the patterns to forbid names
        Since:
        1.4.7

猜你喜欢

转载自zzc1684.iteye.com/blog/2211004