我有一个带有私有字段和公共方法的类。我的方法遵循获取/设置命名约定。当我的字段是私有的并且我尝试将对象数据写入 XML 文件时,我得到一个空的 XML 文件,但是当我将它们更改为公共时,XML 包含所有必要的数据。您认为是什么原因造成的?
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();
这是因为您的方法没有"Setter"
使其成为可访问的"属性"。将方法setMethods(String mName)
更改为addMethod(String mName)
以添加单个方法,并添加与方法和事物工作时间相同的设置器setMethods
。示例如下:
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();
}
}