进阶day10-.static和transient在序列化中的区别与作用
This commit is contained in:
@@ -21,7 +21,7 @@ public class Demo11 {
|
|||||||
Student s = new Student("张三", 20);
|
Student s = new Student("张三", 20);
|
||||||
|
|
||||||
//序列化:将java对象保存到文件中
|
//序列化:将java对象保存到文件中
|
||||||
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("student.txt"));
|
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("student2.txt"));
|
||||||
oos.writeObject(s);
|
oos.writeObject(s);
|
||||||
|
|
||||||
oos.close();
|
oos.close();
|
||||||
|
|||||||
@@ -18,7 +18,7 @@ import java.util.function.Supplier;
|
|||||||
public class Demo12 {
|
public class Demo12 {
|
||||||
//将之前的student.txt读取到java进程中生成一个叫张三,18的Student对象
|
//将之前的student.txt读取到java进程中生成一个叫张三,18的Student对象
|
||||||
public static void main(String[] args) throws IOException, ClassNotFoundException {
|
public static void main(String[] args) throws IOException, ClassNotFoundException {
|
||||||
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("student.txt"));
|
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("student2.txt"));
|
||||||
Object o = ois.readObject();
|
Object o = ois.readObject();
|
||||||
if (o instanceof Student) {
|
if (o instanceof Student) {
|
||||||
Student s = ((Student) o);
|
Student s = ((Student) o);
|
||||||
|
|||||||
@@ -6,7 +6,9 @@ Serializable接口的作用:起到一个标识的作用,确认当前类的
|
|||||||
*/
|
*/
|
||||||
public class Student implements Serializable {
|
public class Student implements Serializable {
|
||||||
String name;
|
String name;
|
||||||
int age;
|
transient int age;//transient:瞬态,在序列化对象时,被它修饰的属性,不能被保存
|
||||||
|
|
||||||
|
static String classroom = "1903";//不会被序列化,静态内容跟着字节码文件,只跟类有关
|
||||||
|
|
||||||
public Student(String name, int age) {
|
public Student(String name, int age) {
|
||||||
this.name = name;
|
this.name = name;
|
||||||
|
|||||||
Reference in New Issue
Block a user