为什么Java有瞬态字段?

本文翻译自: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 object
        o.writeObject(nameStore);
        o.close();

        // reading from object
        ObjectInputStream 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

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值