Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ```java
- package com.fanglian.modules.test.web;
- import java.io.Serializable;
- import java.util.Date;
- public class Person implements Serializable {
- private static final long serialVersionUID = 1L;
- private String name;
- private Integer age;
- private static String address;
- private transient Date birthday;
- public Date getBirthday() {
- return birthday;
- }
- public void setBirthday(Date birthday) {
- this.birthday = birthday;
- }
- public Person(String name, Integer age, Date birthday) {
- this.name = name;
- this.age = age;
- this.birthday = birthday;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public Integer getAge() {
- return age;
- }
- public void setAge(Integer age) {
- this.age = age;
- }
- public static String getAddress() {
- return address;
- }
- public static void setAddress(String address) {
- Person.address = address;
- }
- @Override
- public String toString() {
- return "Person{" +
- "name='" + name + '\'' +
- ", age=" + age +
- '}';
- }
- }
- package com.fanglian.modules.test.web;
- import java.io.*;
- import java.util.Date;
- /**
- * java序列化与反序列化:
- * 序列化:字节序列转换为对象的过程
- * 反序列化:对象转换为字节序列的过程
- * 被transient修饰的属性是不会被序列化的
- * 静态属性也是不能被序列化,和反序列化
- * 可序列化的对象,如果没有指定serialVersionUID,java默认会生产一个serialVersionUID,但是序列化和反序列化生成
- * 的serialVersionUID是不同的,所以推荐手动指定serialVersionUID值,如:
- * private final static long serialVersionUID = 1L;
- * 所以实现Serializable接口的时候,一定要给这个serialVersionUID赋值!
- * 对象序列化机制:是java语言内建的一种持久化方式,通过对象序列化,可以把对象状态保持为字节数组,并且可以在需要的时候
- * 将字节数组反序列化的方式转换成为对象,对象序列化可以很容易的在JVM中活动对象和字节数组之家转换
- * 在java中对象序列化和反序列化被广泛应用到RMI(远程方法调用)以及网络传输中
- */
- public class Test {
- public static void main(String[] args)throws Exception {
- m1();
- Person person = m2();
- System.out.println(person.toString());
- }
- //序列化
- public static void m1()throws Exception {
- Person person = new Person("jack", 22, new Date());
- String path = "C:/Users/Administrator/Desktop/person.txt";
- ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(new File(path)));
- oos.writeObject(person);
- oos.flush();
- oos.close();
- System.out.println("对象序列化完成!");
- }
- //反序列化
- public static Person m2()throws Exception {
- String path = "C:/Users/Administrator/Desktop/person.txt";
- ObjectInputStream ois = new ObjectInputStream(new FileInputStream(new File(path)));
- Person o = (Person) ois.readObject();
- ois.close();
- System.out.println("对象反序列化完成!");
- return o;
- }
- }
- ```
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement