我正在阅读有关transient和final关键字的内容,我找到了一个答案,我们不能使用带有final关键字的transient关键字.我试过并感到困惑,因为这里工作正常.
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;
import java.io.Serializable;
public class SerExample{
public static void main(String... args){
Student foo = new Student(3,2,"ABC");
Student koo = new Student(6,4,"DEF");
try
{
FileOutputStream fos = new FileOutputStream("abc.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(foo);
oos.writeObject(koo);
oos.close();
fos.close();
}
catch(Exception e){/**/}
try{
FileInputStream fis = new FileInputStream("abc.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
System.out.println(ois.readObject());
System.out.println(ois.readObject());
fis.close();
ois.close();
}catch(Exception e){/**/}
}
}
Run Code Online (Sandbox Code Playgroud)
这是Serializable Student类代码:
class Student implements Serializable{
private transient final int id;
private transient …Run Code Online (Sandbox Code Playgroud) 我有一个实现的类,Serializable我通过一个类型的锁对象来保护这个类的不变量Object.是暂时还是可以有任何不必要的副作用?
代码:
class MyClass implements Serializable{
private final transient lock = new Object();
....
}
Run Code Online (Sandbox Code Playgroud)