transient关键字
## 简介 `transient` 翻译:短暂的,转瞬即逝的;暂时的 - 在Java中,一个类只要实
渲染中...
## 简介
`transient` 翻译:短暂的,转瞬即逝的;暂时的
- 在Java中,一个类只要实现了 `Serilizable` 接口,其属性和方法都会被自动序列化。
- 但实际开发中,对象的某些属性可能比较敏感,不便于被序列化从而传输到网络或者本地文件。
- 这时候就可以使用 `transient` 关键字修饰该属性,正如其意,`transient`修饰的对象只会短暂的存在于内存中。
- `transient` 只能修饰属性,不能用于类和方法。
<!-- more -->
参考链接:[transient关键字的作用以及几个疑问的解决](https://blog.csdn.net/Aphysia/article/details/109349613)
## 一个示例
```java
import java.io.*;
// 示例1:使用 transient 修饰实例变量
class MyClass implements Serializable {
// 正常序列化该变量
private int normalVar = 10;
// transient 修饰的变量不会被序列化
private transient String transientVar = "Transient variable";
public void display() {
System.out.println("normalVar: " + normalVar);
System.out.println("transientVar: " + transientVar);
}
}
public class Main {
public static void main(String[] args) {
MyClass obj = new MyClass();
obj.display();
// 将对象序列化到文件
try {
FileOutputStream fileOut = new FileOutputStream("object.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(obj);
out.close();
fileOut.close();
System.out.println("Object serialized successfully.");
} catch (IOException e) {
e.printStackTrace();
}
// 从文件中反序列化对象
try {
FileInputStream fileIn = new FileInputStream("object.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
MyClass newObj = (MyClass) in.readObject();
newObj.display();
in.close();
fileIn.close();
System.out.println("Object deserialized successfully.");
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
```
在上面的示例中,`MyClass` 类实现了 `Serializable` 接口,并包含了一个 `transient` 变量 `transientVar`。在 `main` 方法中,我们创建了一个 `MyClass` 对象并序列化到文件中,然后从文件中反序列化该对象。在对象被序列化和反序列化过程中,`transientVar` 变量的值被忽略,因为它被声明为 `transient`,所以在反序列化后,它的值为 `null`。
END
评论
登录后查看和发表评论
前往登录