我试图在自己的类中使用“ Marshaller”来“对象”和“解组”对象。
主要方法:
public class Main {
public static void main(String[] args) {
new Something();
}
}
“ Something”类将产生要编组或拆组的实例:
import java.io.File;
import java.io.Serializable;
public class Something implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
public int value = 2;
private File file = new File("something.serial");
private static Marshaller marshaller = new Marshaller();
Something() {
value = 3;
marshaller.marshalling(file, this);
Something anotherThing = (Something) marshaller.unmarshalling(file);
System.out.println(anotherThing.value);
}
}
这是Marshaller:
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class Marshaller {
public Marshaller() {
}
/**
* Charge l'objet sérializé d'un fichier si il existe
* @param file : le fichier à désérialiser
* @return obj : l'instance d'objet désérialisé
*/
public Object unmarshalling(File file) {
Object obj = null;
ObjectInputStream ois;
try {
BufferedInputStream bis = new BufferedInputStream(
new FileInputStream(file));
ois = new ObjectInputStream(bis);
obj = ois.readObject();
ois.close();
} catch(FileNotFoundException e) {
e.printStackTrace();
} catch(IOException e) {
e.printStackTrace();
} catch(ClassNotFoundException e) {
e.printStackTrace();
}
return obj;
}
/**
* Permet d'enregistrer un objet (settings, client...) dans un fichier
* @param file : le fichier support de la sérialisation
* @param obj : l'instance d'objet à sérialiser
*
*/
public void marshalling(File file, Object obj) {
ObjectOutputStream oos;
try {
oos = new ObjectOutputStream(
new BufferedOutputStream(
new FileOutputStream(file)));
oos.writeObject(obj);
oos.close();
} catch(IOException e) {
e.printStackTrace();
}
}
}
在类
Something
中,如果未将Marshaller声明为“静态”,则会得到一个java.io.NotSerializableException
。为什么呢感谢您的回答,以帮助我理解。
祝你有美好的一天。
PS:我应该使用
marshall
还是serialize
吗? 最佳答案
序列化对象时,该对象可访问的所有对象也会被存储,因此所有对象都必须为serializable
。如果您将类声明为:
public class Something implements Serializable {
private static final long serialVersionUID = 1L;
public int value = 2;
private File file = new File("something.serial");
private Marshaller marshaller = new Marshaller();
}
然后,来自任何类
Something
的实例的可访问字段是value
,file
和marshaller
,因此jvm也会尝试对它们进行序列化,这要求它们每个必须为serializable
,但是类为Marshaller
否,则发生异常。当您将字段声明为
static
时,您使其成为类的成员,而不是单个实例,因为序列化仅关心实例的当前状态,因此只会对与特定实例关联的数据进行序列化,因此所有静态字段忽略,您的程序运行正常。如果确实需要将字段作为实例成员但不希望对其进行序列化,则需要使用关键字
transient
对其进行声明,那么在序列化期间将忽略该字段。对于
marshall
和serialize
一词,我不是英语母语人士,因此我不能过多地讲述它们之间的区别,但是在这种情况下,我个人更喜欢serialize
并使用marshall
从/向Java对象处理JSON / XML时。希望这对您有所帮助:-)