Brosef
Brosef

Reputation: 3095

XMLEncoder not writing object data when class fields are private

I have a class with private fields and public methods. My methods follow the get/set naming convention. When my fields are private and I try to write my object data to an XML file, I get an empty XML file, but when I change them to public, the XML contains all the necessary data. What do you think is causing this?

public class ClassData {

private String name;
private ArrayList<String> methods;

public ClassData()
{
    methods = new ArrayList<>();
}

public void setName(String cName)
{
    name = cName;
}

public String getName()
{
    return name;
}

public void setMethods(String mName)
{
    methods.add(mName);    
}

public ArrayList<String> getMethods()
{
    return methods;
}

}

String fileName = cObj.getName() + ".xml";

XMLEncoder enc=null;

try{
    enc=new XMLEncoder(new BufferedOutputStream(new FileOutputStream(fileName)));
}catch(FileNotFoundException fileNotFound){
    System.out.println("Unable to save file.");
}

enc.writeObject(cObj);
enc.close();

Upvotes: 0

Views: 1323

Answers (1)

Optional
Optional

Reputation: 4507

This is because your methods do not have a "Setter" to make it an accessible "property". Change method setMethods(String mName) to addMethod(String mName) to add individual method and add a setter setMethods that sets same time as that of methods and things work. Sample below:

import java.beans.XMLEncoder;
import java.io.BufferedOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.ArrayList;

public class ClassData {

    private String name;
    private ArrayList<String> methods;

    public ClassData() {
        methods = new ArrayList<>();
    }

    public void setName(String cName) {
        name = cName;
    }

    public String getName() {
        return name;
    }

    public void addMethod(String mName) {
        methods.add(mName);
    }
    public void setMethods(ArrayList<String> m)
    {
        methods.addAll(m);
    }

    public ArrayList<String> getMethods() {
        return methods;
    }

    public static void main(String[] args) {
        ClassData cObj = new ClassData();
        cObj.setName("This_is_name");
        cObj.addMethod("m1");
        String fileName = cObj.getName() + ".xml";

        XMLEncoder enc = null;

        try {
            enc = new XMLEncoder(new BufferedOutputStream(new FileOutputStream(fileName)));
        } catch (FileNotFoundException fileNotFound) {
            System.out.println("Unable to save file.");
        }

        enc.writeObject(cObj);
        enc.close();

    }

}

Upvotes: 3

Related Questions