How to use the Serializable interface to implement serialization in java

王林
Release: 2020-04-28 17:51:15
forward
2215 people have browsed it

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 + "}";
	}
}
Copy after login
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
		}
	}
}
Copy after login

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
Copy after login

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!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!