We all know Java allows us to create reusable objects in memory.
However, all of those objects exist only as long as the virtual machine
remains running. It would be nice if the objects we create could exist
beyond the lifetime of the virtual machine, wouldn't it? Well, with
object serialization, you can flatten your objects and reuse them in
powerful ways.
Object
serialization is the process of saving an object's state to a sequence
of bytes, as well as the process of rebuilding those bytes into a live
object at some future time. The Java Serialization API provides a
standard mechanism for Java developers to handle object serialization.
The API is small and easy to use, provided the classes and methods are
understood.
Throughout this
article, we'll examine how to persist your Java objects, starting with
the basics and proceeding to the more advanced concepts. We'll learn
three different ways to perform serialization -- using the default
protocol, customizing the default protocol, and creating our own
protocol -- and we'll investigate concerns that arise with any
persistence scheme such as object caching, version control, and
performance issues.
By the conclusion of this article, you should have a solid comprehension of that powerful yet sometimes poorly understood
Java API.
First things first: The default mechanism
Let's start with the basics. To persist an object in Java, we must have a persistent object. An object is marked serializable
by implementing the java.io.Serializable
interface, which signifies to the underlying API that the object can be flattened into bytes and subsequently inflated in
the future.
Let's look at a persistent class we'll use to demonstrate the serialization mechanism:
10 import java.io.Serializable;
20 import java.util.Date;
30 import java.util.Calendar;
40 public class PersistentTime implements Serializable
50 {
60 private Date time;
70
80 public PersistentTime()
90 {
100 time = Calendar.getInstance().getTime();
110 }
120
130 public Date getTime()
140 {
150 return time;
160 }
170 }
As you can see, the only thing we had to do differently from creating a normal class is implement the java.io.Serializable
interface on line 40. The completely empty Serializable
is only a marker
interface -- it simply allows the serialization mechanism to verify that the class is able to be persisted. Thus, we turn
to the first rule of serialization:
Rule #1: The object to be persisted must implement the Serializable
interface or inherit that implementation from its object hierarchy.
The next step is to actually persist the object. That is done with the java.io.ObjectOutputStream
class. That class is a filter stream
-- it is wrapped around a lower-level byte stream (called a node stream
)
to handle the serialization protocol for us. Node streams can be used
to write to file systems or even across sockets. That means we could
easily transfer a flattened object across a network wire and have it be
rebuilt on the other side!
Take a look at the code used to save the PersistentTime
object:
10 import java.io.ObjectOutputStream;
20 import java.io.FileOutputStream;
30 import java.io.IOException;
40 public class FlattenTime
50 {
60 public static void main(String [] args)
70 {
80 String filename = "time.ser";
90 if(args.length > 0)
100 {
110 filename = args[0];
120 }
130 PersistentTime time = new PersistentTime();
140 FileOutputStream fos = null;
150 ObjectOutputStream out = null;
160 try
170 {
180 fos = new FileOutputStream(filename);
190 out = new ObjectOutputStream(fos);
200 out.writeObject(time);
210 out.close();
220 }
230 catch(IOException ex)
240 {
250 ex.printStackTrace();
260 }
270 }
280 }
The real work happens on line 200 when we call the ObjectOutputStream.writeObject()
method, which kicks off the serialization mechanism and the object is flattened (in that case to a file).
To restore the file, we can employ the following code:
10 import java.io.ObjectInputStream;
20 import java.io.FileInputStream;
30 import java.io.IOException;
40 import java.util.Calendar;
50 public class InflateTime
60 {
70 public static void main(String [] args)
80 {
90 String filename = "time.ser";
100 if(args.length > 0)
110 {
120 filename = args[0];
130 }
140 PersistentTime time = null;
150 FileInputStream fis = null;
160 ObjectInputStream in = null;
170 try
180 {
190 fis = new FileInputStream(filename);
200 in = new ObjectInputStream(fis);
210 time = (PersistentTime)in.readObject();
220 in.close();
230 }
240 catch(IOException ex)
250 {
260 ex.printStackTrace();
270 }
280 catch(ClassNotFoundException ex)
290 {
300 ex.printStackTrace();
310 }
320 // print out restored time
330 System.out.println("Flattened time: " + time.getTime());
340 System.out.println();
350 // print out the current time
360 System.out.println("Current time: " + Calendar.getInstance().getTime());
370 }
380}
In the code above, the object's restoration occurs on line 210 with the ObjectInputStream.readObject()
method call. The method call reads in the raw bytes that we previously persisted and creates a live object that is an exact
replica of the original. Because readObject()
can read any serializable object, a cast to the correct type is
required. With that in mind, the class file must be accessible from the
system in which the restoration occurs. In other words, the object's
class file and methods are not saved; only the object's state
is saved.
Later, on line 360, we simply call the getTime()
method to retrieve the time that the original object flattened. The flatten time is compared to the current time to demonstrate
that the mechanism indeed worked as expected.
分享到:
相关推荐
"flatten"这个包就是实现这一功能的工具。 1. **Laravel框架基础**:Laravel是一款基于PHP的开源Web应用框架,遵循MVC(模型-视图-控制器)架构模式,以其优雅的语法和丰富的功能库而闻名。开发者可以利用Laravel...
geojson-flatten 将文件中的MultiPoint,MultiPolygon,MultiLineString和GeometryCollection几何图形展平为简单的非复杂几何图形。 如果传入FeatureCollection,则返回FeatureCollection。 如果传入单个功能,则...
【flatten_2.0】是Lighthouse3D网站GLSL教程第三部分的一个示例项目,主要涉及图形编程领域,特别是OpenGL着色语言(GLSL)的应用。GLSL是一种用于GPU编程的语言,允许开发者直接在图形处理器上编写计算密集型代码,...
标题“Tool for Flatten A Folder”指的是一个用于整理和扁平化文件夹结构的命令行工具。这个工具的主要功能是帮助用户将多个不同目录下的特定文件复制到一个单一的目标目录中,从而实现文件夹的扁平化,使得文件...
资源分类:Python库 所属语言:Python 资源全名:flatten_json-0.1.12.tar.gz 资源来源:官方 安装方法:https://lanzao.blog.csdn.net/article/details/101784059
flatten_gds.tcl
MojoHaus Flatten Maven插件 这是 。 1.0.x分支: 快速开始 这个插件会生成您pom.xml的扁平版本,并使maven可以安装和部署该版本,而不是原始pom.xml。 <groupId>org.codehaus.mojo <artifactId>flatten-...
Python中的flatten()函数主要用于数组或矩阵的降维操作,即将多维的数组或矩阵压缩成一维的形式。这个函数是numpy库中ndarray对象的一个方法。numpy是Python中进行科学计算的核心库,提供了高性能的多维数组对象及一...
Flatten Maven插件 生产发布 开发发布 安装 相似的插件 插件功能 取代公开的身份 解决依赖版本范围 根据范围排除依赖项 可选地包括传递依赖 根据xml标签名称删除pom.xml成员 用生成的pom.xml.flatten切换项目pom....
"obj-flatten"是一个专门用于对象展平的开源库,它能够将具有嵌套结构的对象转换成一个扁平化的对象,这在处理复杂的数据交互和优化数据操作时非常有用。本文将深入探讨这个库的工作原理、应用场景以及如何使用它。 ...
import { flatten } from "array-flatten" ; flatten ( [ 1 , [ 2 , [ 3 , [ 4 , [ 5 ] , 6 ] , 7 ] , 8 ] , 9 ] ) ; //=> [1, 2, 3, 4, 5, 6, 7, 8, 9] ( function ( ) { flatten ( arguments ) ; //=> [1, 2, 3] ...
### numpy下的flatten()函数用法详解 #### 一、引言 在数据分析和科学计算领域,NumPy 是一个广泛使用的库,它提供了大量的数学函数来处理数组数据。其中一个常用的功能是将多维数组转换为一维数组,这通常称为...
flatten-js是一个JavaScript库,用于处理抽象的几何形状,例如点,矢量,线,射线,线段,圆,弧和多边形。 形状可以组织成“平面集”-支持空间查询的可搜索容器。 flatten-js提供了许多有用的方法和算法,例如查找...
在JavaScript编程中,"flatten"通常指的是将一个多维数组转换为单层扁平化数组的过程。这个过程在处理复杂的数据结构时非常有用,比如当你需要遍历或操作嵌套数组中的所有元素时。本篇文章将深入探讨JavaScript中...
这里讨论的是如何拍平(flatten)一个多维数组,即将嵌套的数组展开为一维数组。在最新的ECMAScript规范中,确实引入了`flat()`方法来解决这个问题,但在这里我们关注的是手动实现这一功能的方法。 首先,我们来看`...
例如,我有一个padding过的矩阵,那么它一定是带masking的,然后我想要把它Flatten,再输入到Dense层。然而Keras的Flatten层不支持masking。 Keras原本Flatten的实现 class Flatten(Layer): def __init__(self, **...
`jsonpath_flatten`库就是为了解决这个问题而设计的。 `jsonpath_flatten`库允许开发者通过JSONPath表达式来指定哪些键需要被展开,然后将这些键对应的值拼接成一个单层字典。这在处理大数据、报表生成或者数据分析...
import flatten , { isLast } from 'object-flatten'const flattened = flatten ( isLast , { margin : { auto : { marginLeft : 'auto' , marginRight : 'auto' } }} ) 这将返回一个展平的对象: { 'margin.auto' ...