java 对象序列化是什么_Java什么是对象序列化?

小编典典

你可以将序列化视为将对象实例转换为字节序列(取决于实现的二进制或非二进制)的过程。

当你要通过网络传输一个对象数据(例如从一个JVM传输到另一个JVM)时,此功能非常有用。

在Java中,平台内置了序列化机制,但是你需要实现Serializable接口才能使对象可序列化。

你还可以通过将属性标记为transient来防止对象中的某些数据被序列化。

最后,你可以覆盖默认机制,并提供自己的机制。这在某些特殊情况下可能是合适的。为此,你可以使用java中的隐藏功能之一。

重要的是要注意,序列化的是对象的“值”或内容,而不是类定义。因此,方法未序列化。

这是一个非常基本的示例,带有注释以方便阅读:

import java.io.*;

import java.util.*;

// This class implements "Serializable" to let the system know

// it's ok to do it. You as programmer are aware of that.

public class SerializationSample implements Serializable {

// These attributes conform the "value" of the object.

// These two will be serialized;

private String aString = "The value of that string";

private int someInteger = 0;

// But this won't since it is marked as transient.

private transient List unInterestingLongLongList;

// Main method to test.

public static void main( String [] args ) throws IOException {

// Create a sample object, that contains the default values.

SerializationSample instance = new SerializationSample();

// The "ObjectOutputStream" class has the default

// definition to serialize an object.

ObjectOutputStream oos = new ObjectOutputStream(

// By using "FileOutputStream" we will

// Write it to a File in the file system

// It could have been a Socket to another

// machine, a database, an in memory array, etc.

new FileOutputStream(new File("o.ser")));

// do the magic

oos.writeObject( instance );

// close the writing.

oos.close();

}

}

当我们运行该程序时,将创建文件“ o.ser”,我们可以看到后面发生了什么。

如果我们将someInteger的值更改为例如Integer.MAX_VALUE,则可以比较输出以查看差异。

2020-02-26

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值