XMLEncoder writeObject跳过在构造函数中初始化的属性

时间:2016-12-31 04:47:58

标签: java xmlencoder

XMLEncoder如何知道在对象的构造函数中设置了属性,从而避免输出它?

这是一个简单的例子(在Java 1.8上运行),它演示了这个: 首先使用getter和setter以及默认构造函数定义一个简单对象:

public double GetInStockQuantity(Warehouse warehouse, Entities db)
{
    double res;
    try
    {
        res = db.Stocks.AsNoTracking().Where(c => c.Product.ID == ID && c.WarehouseID == warehouse.ID).
            AsNoTracking().AsEnumerable().
            SkipWhile(c => c.InvoiceItems.Any(q => q.Invoice.IsStocked == false)).Sum(q => q.Quantity);
    }
    catch (Exception)
    {
        res = 0;
    }
    return res;
}

现在,实例化对象的main使用其中一个属性的setter,并在最终对象上调用XMLEncoder。为了确保我在调用编码器之前还打印了对象的属性:

public class Simple {
 int m;
 int n;

 public int getM() { return m;}
 public void setM(int m) {this.m = m;}
 public int getN() {return n;}
 public void setN(int n) {this.n = n;   }

 public String toString() {
    return "m=" + m + ",n=" + n;
 }  

 public Simple() {
    this.m = 1;
    this.n = 2;
 }      
}

运行程序,我得到了预期的输出: M = 1,N = 7 但是,当我查看生成的文件时,我得到:

public class Main {

 public static void main(String[] args) {
    Simple simple = new Simple();

    simple.setN(7);
    System.out.println(simple.toString());

    XMLEncoder encoder=null;
    try{
        encoder=new XMLEncoder(new BufferedOutputStream(
                        new FileOutputStream("simple.xml")));
    }catch(FileNotFoundException fileNotFound){
        System.out.println("ERROR: While Creating the File ");
    }
    encoder.writeObject(simple);
    encoder.close();
  }
 }

这里我们看到XMLEncoder只输出了一个属性,而前一个对象的打印输出显示两个属性都设置了它们的值。就好像XMLEncoder有一个水晶球,知道过去发生了什么!

1 个答案:

答案 0 :(得分:0)

它实际上看起来恰恰相反,好像它有健忘症一样,它可以同时输出n和m,但它只打印一个属性,即受你的setter影响的属性。

但是Official doc

  

结构紧凑:XMLEncoder类使用冗余   内部消除算法使a的默认值   Bean的属性不会写入流。

因此它解释了它的选择性