⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 e009. preventing a bean property from being serialized to xml.txt

📁 这里面包含了一百多个JAVA源文件
💻 TXT
字号:
By default, when serializing an object into XML, the current value of all public properties is persisted (if they don't equal the default value). This example demonstrates how to prevent a public property from being persisted. 
See also e8 Deserializing a Bean from XML. 

    // Create an object and set properties
    MyClass2 o = new MyClass2();
    o.setProp(1);
    o.setProps(new int[]{1, 2, 3});
    
    try {
        // Serialize object into XML.
        // props is transient so it will not be persisted.
        XMLEncoder encoder = new XMLEncoder(new BufferedOutputStream(
            new FileOutputStream("outfilename.xml")));
        encoder.writeObject(o);
        encoder.close();
    } catch (FileNotFoundException e) {
    }

    // This class defines two properties - prop and props.
    // The props property is marked transient so that it will not
    // be persisted if serialized into XML.
    import java.beans.*;
    public class MyClass2 {
        // The prop property
        int i;
        public int getProp() {
            return i;
        }
        public void setProp(int i) {
            this.i = i;
        }
    
        // The props property
        int[] iarray = new int[0];
        public int[] getProps() {
            return iarray;
        }
        public void setProps(int[] iarray) {
            this.iarray = iarray;
        }
    
        static {
            try {
                // Make the props property transient
                BeanInfo info = Introspector.getBeanInfo(MyClass2.class);
                PropertyDescriptor[] propertyDescriptors = info.getPropertyDescriptors();
                for (int i = 0; i < propertyDescriptors.length; ++i) {
                    PropertyDescriptor pd = propertyDescriptors[i];
                    if (pd.getName().equals("props")) {
                        pd.setValue("transient", Boolean.TRUE);
                    }
                }
            } catch (IntrospectionException e) {
            }
        }
    }

Here is the XML data: 
    <?xml version="1.0" encoding="UTF-8"?>
    <java version="1.4.0" class="java.beans.XMLDecoder">
        <object class="MyClass2">
            <void property="prop">
                <int>1</int>
            </void>
        </object>
    </java>

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -