Serializing an Immutable Bean Property to XML - Java Object Oriented Design

Java examples for Object Oriented Design:Java Bean

Description

Serializing an Immutable Bean Property to XML

Demo Code


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 {//w w w. j a  va  2  s .c o m
      XMLEncoder encoder = new XMLEncoder(new BufferedOutputStream(
          new FileOutputStream("outfilename.xml")));

      String[] propertyNames = new String[] { "prop" };
      encoder.setPersistenceDelegate(MyClass.class,
          new DefaultPersistenceDelegate(propertyNames));

      encoder.writeObject(o);
      encoder.close();
    } catch (FileNotFoundException e) {
    }
  }
}

class MyClass {
  int prop;

  // The constructor that initializes the immutable property prop
  public MyClass(int prop) {
    this.prop = prop;
  }

  // The immutable property
  public int getProp() {
    return prop;
  }
}

Result


Related Tutorials