集册 Java实例教程 将不可变Bean属性序列化为XML

将不可变Bean属性序列化为XML

欢马劈雪     最近更新时间:2020-01-02 10:19:05

369
将不可变Bean属性序列化为XML
/*来 自 时 代 J a v a 公 众 号*/


import java.beans.DefaultPersistenceDelegate;

import java.beans.XMLEncoder;

import java.io.BufferedOutputStream;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;


public class Main {

  public static void main(String[] args) {

    MyClass o = new MyClass(123);

    try {

      XMLEncoder encoder = new XMLEncoder(new BufferedOutputStream(

          new FileOutputStream("outfilename.xml")));


      String[] propertyNames = new String[] { "prop" };

      encoder.setPersistenceDelegate(MyClass.class,/** 时 代 J a v a 公 众 号 - nowjava.com 提 供 **/

          new DefaultPersistenceDelegate(propertyNames));


      encoder.writeObject(o);

      encoder.close();

    } catch (FileNotFoundException e) {

    }

  }

}


class MyClass {

  int prop;


  // The constructor that initializes the immutable property prop

  
展开阅读全文