为什么在java中使用`transient`关键字? [英] Why use the `transient` keyword in java?

查看:242
本文介绍了为什么在java中使用`transient`关键字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在java中的 private 修饰符之前有一个与 transient 关键字相关的问题。

I have an issue related to the transient keyword's use before the private modifier in java .

变量声明:

transient private ResourceBundle pageResourceBundle; 

当我用谷歌搜索它时,我在下面找到了这些文档,但它们正在谈论序列化。实际上我的班级没有实现任何序列化。

When I Googled it, I found these docs below, but they're talking about serialized. Actually my class does not implement any serialized.

更多信息:


http://java91.blogspot.in/ 2017/01 / why-does-java-have-transient-fields.html

我的课程如下所示:

public class LoginViewModel extends AbstractViewModel {

    transient private ResourceBundle pageResourceBundle;

    @AfterCompose
    public void afterCompose(@ContextParam(ContextType.VIEW) Component view) {
        initializeLoginValues();
        boolean timeout = BooleanUtils.toBoolean(getHttpServletRequest().getParameter("timeout"));
        if (timeout) {
            Messagebox.show(pageResourceBundle.getText("MSG_SESSION_HAS_EXPIRED_PLEASE_LOGIN"), pageResourceBundle.getText("LABEL_ALERT"),
                    Messagebox.OK, Messagebox.ERROR);
        }
        view.getPage().setTitle(CsdcLicence.get().getApplicationName());
    }

我有一些问题。

1.为什么在私有变量之前使用 transient 关键字?

1.why use the transient keyword before a private variable?

2.目的是什么使用此关键字?

2.what is the purpose of using this keyword?

推荐答案

瞬态变量永远不会在java中序列化。

transient variables are never serialized in java.

它标记一个成员变量,当它被持久化为字节流时不被序列化。当通过网络传输对象时,该对象需要序列化。序列化将对象状态转换为串行字节。这些字节通过网络发送,并从这些字节重新创建对象。由java transient关键字标记的成员变量不会被转移,它们会被故意丢失。

It marks a member variable not to be serialized when it is persisted to streams of bytes. When an object is transferred through the network, the object needs to be 'serialized'. Serialization converts the object state to serial bytes. Those bytes are sent over the network and the object is recreated from those bytes. Member variables marked by the java transient keyword are not transferred, they are lost intentionally.

请查看序列化是。?并且还可以参考这个

please have a look at what serialization is.? and also refer this

示例

public class Foo implements Serializable
{
  private String saveMe;
  private transient String dontSaveMe;
  private transient String password;
  //...
}

上面的示例 dontSaveMe & 密码永远不会被序列化,因为它们被声明为瞬态变量

In above example dontSaveMe & password are never get serialize as they are declare as a transient variables.

这篇关于为什么在java中使用`transient`关键字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆