集册 Java实例教程 防止将Bean属性序列化为XML

防止将Bean属性序列化为XML

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

430
防止将Bean属性序列化为XML


import java.beans.BeanInfo;/** from 时代Java公众号 - nowjava.com**/

import java.beans.IntrospectionException;

import java.beans.Introspector;

import java.beans.PropertyDescriptor;

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) {

    // Create an object and set properties

    MyClass2 o = new MyClass2();

    o.setProp(1);

    o.setProps(new int[] { 1, 2, 3 });
    /*
    时代Java公众号
    */


    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) {

    }

  }


}


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[] propertyDescripto
展开阅读全文