本文翻译自:Why does Java have transient fields?

为什么Java有瞬态字段?


#1楼

参考:https://stackoom.com/question/3opS/为什么Java有瞬态字段


#2楼

Before understanding the transient keyword, one has to understand the concept of serialization. 在理解transient关键字之前,必须先了解序列化的概念。 If the reader knows about serialization, please skip the first point. 如果读者知道序列化,请跳过第一点。

What is serialization? 什么是序列化?

Serialization is the process of making the object's state persistent. 序列化是使对象的状态持久化的过程。 That means the state of the object is converted into a stream of bytes to be used for persisting (eg storing bytes in a file) or transferring (eg sending bytes across a network). 这意味着对象的状态被转换为字节流,用于持久化(例如,将文件存储在文件中)或传输(例如,通过网络发送字节)。 In the same way, we can use the deserialization to bring back the object's state from bytes. 以同样的方式,我们可以使用反序列化从字节中恢复对象的状态。 This is one of the important concepts in Java programming because serialization is mostly used in networking programming. 这是Java编程中的重要概念之一,因为序列化主要用于网络编程。 The objects that need to be transmitted through the network have to be converted into bytes. 需要通过网络传输的对象必须转换为字节。 For that purpose, every class or interface must implement the Serializable interface. 为此,每个类或接口都必须实现Serializable接口。 It is a marker interface without any methods. 它是没有任何方法的标记界面。

Now what is the transient keyword and its purpose? 现在什么是transient关键字及其目的?

By default, all of object's variables get converted into a persistent state. 默认情况下,所有对象的变量都转换为持久状态。 In some cases, you may want to avoid persisting some variables because you don't have the need to persist those variables. 在某些情况下,您可能希望避免持久化某些变量,因为您不需要持久保存这些变量。 So you can declare those variables as transient . 因此,您可以将这些变量声明为transient变量。 If the variable is declared as transient , then it will not be persisted. 如果变量被声明为transient变量,那么它将不会被持久化。 That is the main purpose of the transient keyword. 这是transient关键字的主要目的。

I want to explain the above two points with the following example: 我想通过以下示例解释上述两点:

package javabeat.samples;import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;class NameStore implements Serializable{private String firstName;private transient String middleName;private String lastName;public NameStore (String fName, String mName, String lName){this.firstName = fName;this.middleName = mName;this.lastName = lName;}public String toString(){StringBuffer sb = new StringBuffer(40);sb.append("First Name : ");sb.append(this.firstName);sb.append("Middle Name : ");sb.append(this.middleName);sb.append("Last Name : ");sb.append(this.lastName);return sb.toString();}
}public class TransientExample{public static void main(String args[]) throws Exception {NameStore nameStore = new NameStore("Steve", "Middle","Jobs");ObjectOutputStream o = new ObjectOutputStream(new FileOutputStream("nameStore"));// writing to objecto.writeObject(nameStore);o.close();// reading from objectObjectInputStream in = new ObjectInputStream(new FileInputStream("nameStore"));NameStore nameStore1 = (NameStore)in.readObject();System.out.println(nameStore1);}
}

And the output will be the following: 输出将如下:

First Name : Steve
Middle Name : null
Last Name : Jobs

Middle Name is declared as transient , so it will not be stored in the persistent storage. 中间名声明为transient ,因此不会存储在持久存储中。

Source 资源


#3楼

My small contribution : 我的小贡献:

What is a transient field? 什么是瞬态场?
Basically, any field modified with the transient keyword is a transient field. 基本上,使用transient关键字修改的任何字段都是瞬态字段。

Why are transient fields needed in Java? 为什么Java中需要瞬态字段?
The transient keyword gives you some control over the serialization process and allows you to exclude some object properties from this process. transient关键字使您可以控制序列化过程,并允许您从此过程中排除某些对象属性。 The serialization process is used to persist Java objects, mostly so that their states can be preserved while they are transferred or inactive. 序列化过程用于持久化Java对象,主要是为了在传输或非活动状态时保留它们的状态。 Sometimes, it makes sense not to serialize certain attributes of an object. 有时,不序列化对象的某些属性是有意义的。

Which fields should you mark transient? 您应该在哪些字段标记瞬态?
Now we know the purpose of the transient keyword and transient fields, it's important to know which fields to mark transient. 现在我们知道transient关键字和瞬态字段的用途,了解哪些字段标记瞬态非常重要。 Static fields aren't serialized either, so the corresponding keyword would also do the trick. 静态字段也没有序列化,因此相应的关键字也可以实现。 But this might ruin your class design; 但这可能会破坏你的课堂设计; this is where the transient keyword comes to the rescue. 这是transient关键字拯救的地方。 I try not to allow fields whose values can be derived from others to be serialized, so I mark them transient. 我尽量不允许其值可以从其他字段派生的字段被序列化,所以我将它们标记为瞬态。 If you have a field called interest whose value can be calculated from other fields ( principal , rate & time ), there is no need to serialize it. 如果您有一个名为interest的字段,其值可以从其他字段( principalratetime )计算,则无需序列化它。

Another good example is with article word counts. 另一个很好的例子是文章字数。 If you are saving an entire article, there's really no need to save the word count, because it can be computed when article gets "deserialized." 如果要保存整篇文章,则实际上不需要保存单词计数,因为可以在文章被“反序列化”时计算。 Or think about loggers; 或者想想伐木工; Logger instances almost never need to be serialized, so they can be made transient. Logger实例几乎从不需要序列化,因此它们可以是瞬态的。


#4楼

transient is used to indicate that a class field doesn't need to be serialized. transient用于指示类字段不需要序列化。 Probably the best example is a Thread field. 可能最好的例子是Thread字段。 There's usually no reason to serialize a Thread , as its state is very 'flow specific'. 通常没有理由将序列化一个Thread ,因为它的状态非常“特定于流”。


#5楼

As per google transient meaning == lasting only for a short time; 根据谷歌暂时意义==只持续很短的时间; impermanent. 暂时的。

Now if you want to make anything transient in java use transient keyword. 现在,如果你想在java中做任何瞬态使用transient关键字。

Q: where to use transient? 问:在哪里使用瞬态?

A: Generally in java we can save data to files by acquiring them in variables and writing those variables to files, this process is known as Serialization. 答:通常在java中,我们可以通过在变量中获取数据并将这些变量写入文件来将数据保存到文件中,这个过程称为序列化。 Now if we want to avoid variable data to be written to file, we would make that variable as transient. 现在,如果我们想要避免将可变数据写入文件,我们会将该变量设置为瞬态。

transient int result=10;

Note: transient variables cannot be local. 注意:瞬态变量不能是本地的。


#6楼

Before I respond to this question, I must explain to you the SERIALIZATION , because if you understand what it means serialization in science computer you can easily understand this keyword. 在回答这个问题之前,我必须向您解释SERIALIZATION ,因为如果您了解科学计算机中序列化的含义,您就可以轻松理解这个关键字。

Serialization When an object is transferred through the network / saved on physical media(file,...), the object must be "serialized". 序列化当对象通过网络传输/保存在物理介质(文件,...)上时,对象必须“序列化”。 Serialization converts byte status object series. 序列化转换字节状态对象系列。 These bytes are sent on the network/saved and the object is re-created from these bytes. 这些字节在网络上发送/保存,并从这些字节重新创建对象。
Example

public class Foo implements Serializable
{private String attr1;private String attr2;...
}

Now IF YOU WANT TO do NOT TRANSFERT / SAVED field of this object SO , you can use keyword transient 现在,如果你想这样做,对象不TRANSFERT / SAVED的话 ,你可以使用关键字 transient

private transient attr2;

Example

为什么Java有瞬态字段?相关推荐

  1. Spring WebClient和Java日期时间字段

    WebClient是Spring Framework的反应式客户端,用于进行服务到服务的调用. WebClient已成为我的实用工具,但是最近我意外地遇到了一个问题,即它处理Java 8时间字段的方式 ...

  2. 读取Java源文件中字段的注释当做Swagger的字段描述

    本文作者:suxingrui 本文链接:https://blog.csdn.net/suxingrui/article/details/103788530 版权声明:本文为原创文章,转载请注明出处. ...

  3. Java bean中字段命名潜规则,前两个字母要么都大写,要么都小写

    Java bean中字段命名潜规则,前两个字母要么都大写,要么都小写,否则会出错 以下代码是获取字段名的源码,根据这段代码可以得知: 输入         输出 AA             AA A ...

  4. java反射字段6,java反射判断字段类型

    java动态获取字段类型,深入理解 Java 虚拟机 Java内存区域与内存溢出异常,java反射判断字段类型,java动态添加字段原理 利用java反射获取泛型类的类型参数具体类对象_计算机软件及应 ...

  5. java读取clob字段的几种方法

    java读取clob字段的几种方法 讲道理,以前压根就没发现数据库中的clob字段和别的字段有什么区别,直到今天一下整出了一点小毛病,才去认真研究了一下. CLOB与BLOB的区别: BLOB和CLO ...

  6. Java实体类字段类型与MySQL数据库字段类型的对应关系

    序号 Java实体类类型 Java引入 MySQL字段类型 1 String java.lang.String varchar 2 String java.lang.String char 3 Str ...

  7. springboot使用Mybatis-plus3.5.0 数据库取日期数据映射java 类LocalDateTime字段 为null

    问题描述 提示:问题: 数据库字段 :DATETIME Java 实体类 字段 LocalDateTime 用查询语句查询出来的日期字段为null 即使 使用 @TableField(value = ...

  8. Java –什么是瞬态字段?

    在Java中, transient字段在序列化过程中被排除. 简而言之,当我们将对象保存到文件中(序列化)时,所有transient字段都将被忽略. 1. POJO +瞬态 复查以下Person类: ...

  9. Java反射 - 私有字段和方法

    尽管普遍认为通过Java Reflection可以访问其他类的私有字段和方法. 这并不困难. 这在单元测试中可以非常方便. 本文将告诉你如何. 访问私有字段 要访问私有字段,您需要调用Class.ge ...

最新文章

  1. OAuth的MVC实现(微软)
  2. 你提交代码前没有校验?巧用gitHooks解决
  3. 使用EntityFrameworkCore实现Repository, UnitOfWork,支持MySQL分库分表
  4. iOS正则表达式(亲测,持续更新)
  5. BIO,NIO,AIO
  6. python四大高阶函数_四大高阶函数
  7. Win2003打不开https的问题
  8. UVA 11054 Wine trading in Gergovia
  9. js、jQuery实现自定义弹出框效果
  10. 生成整数自增ID(集群主键生成服务)
  11. 【2021最新】4篇图神经网络综述论文,建议收藏!
  12. 技术动态 | 不确定性知识图谱的表示和推理
  13. RabbitMQ 工作模式二
  14. windows计算机查看里设置,windows10电脑配置怎么查看
  15. 什么是IaaS PaaS SaaS,看这一篇就够了
  16. 用代码写个烟花之基础版
  17. python实现base64解码_Python实现base64编码解码
  18. Halcon面阵相机采像
  19. 信汇、电汇和票汇的概念、程序及其异同点
  20. Mac开发利器之程序员编辑器MacVim学习总结(转)

热门文章

  1. Linux内核分析之搭建Mykernel
  2. 反素数(高合成数?)
  3. log4j:WARN Please initialize the log4j system properly解决办法
  4. 使用剪切板[4]: 如果把子控件一起复制? - 同时回复 ghd2004 的问题
  5. Ubuntu下配置D-Link路由器进行联网
  6. tomcat中gzip压缩
  7. 数据类型转换(面试题)
  8. Spring Security 3.0控制一个帐号只允许登录一次的问题
  9. SqlCommand.ExecuteReader 方法
  10. Zabbix agent批量自动部署