search
HomeJavaJavagetting StartedHow to use the Serializable interface to implement serialization in java

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. If there is any infringement, please contact admin@php.cn delete

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor