Home  >  Article  >  Java  >  How to use the Serializable interface to implement serialization in java

How to use the Serializable interface to implement serialization in java

王林
王林forward
2020-04-28 17:51:152342browse

How to use the Serializable interface to implement serialization in java

The Serializable interface is a marker interface that does not need to implement any methods. Once a class implements this method, the objects of that class are serializable.

(Recommended video tutorial: java video)

Specific steps:

1. Create an ObjectOutputStream output stream;

2 , call writeObject () of the OjectOutputSteam object to output the serializable object.

public class Person implements Serializable {
	private String name;
	private String age;

	public Person() {
		System.out.println("调用Person的无参构造函数");
	}

	public Person(String name, String age) {
		this.name = name;
		this.age = age;
		System.out.println("调用Person的有参构造函数");
	}

	@Override
	public String toString() {
		// TODO 自动生成的方法存根
		return "Person{'name' :" + name + ",'age' :" + age + "}";
	}
}
public class WriteObject {
	public static void main(String[] args) {
		try {
			ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("Person.txt"));
			Person p = new Person("baby", "12");
			oos.writeObject(p);
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
}

The output is as follows:

aced 0005 7372 0017 7365 7269 616c 697a
6162 6c65 5465 7374 2e50 6572 736f 6e4e
aff9 165f 38dd f602 0002 4c00 0361 6765
7400 124c 6a61 7661 2f6c 616e 672f 5374
7269 6e67 3b4c 0004 6e61 6d65 7100 7e00
0178 7074 0002 3132 7400 0462 6162 79

Recommended tutorial: java entry program

The above is the detailed content of How to use the Serializable interface to implement serialization in java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete