使用@Transient可以让字段不序列化---你知道吗?

书欣 Java经验 发布时间:2022-10-09 21:15:31 阅读数:13506 1
下文笔者讲述@transient关键字在Java序列化中的用途---如下所示

Java 序列化

我们都知道在对象的传输中,我们必须对对象进行序列化
 然后才能进行传输
那么有时候,有些字段我们不想被序列化,那么此时该如何处理呢?
此时我们只需在字段上加入@Transient注解即可
例:
import javax.persistence.Transient;

public class TestJava{
    @Transient
    private String info;
    
    .....get set 方法 ......
}

transient关键字的功能

当对象序列化时,如果不想指定字段写入到目标文件中
此时我们就可以使用@transient注解阻止关键字变量持久化
例:
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
 
class TestClass implements Serializable {
    private transient InputStream is;
 
    private int majorVer;
    private int minorVer;
 
    TestClass(InputStream is) throws IOException {
        System.out.println("TestClass(InputStream) 调用");
        this.is = is;
        DataInputStream dis;
        if (is instanceof DataInputStream)
            dis = (DataInputStream) is;
        else
            dis = new DataInputStream(is);
        if (dis.readInt() != 0xcafebabe)
            throw new IOException("not a .class file");
        minorVer = dis.readShort();
        majorVer = dis.readShort();
    }
 
    int getMajorVer() {
        return majorVer;
    }
 
    int getMinorVer() {
        return minorVer;
    }
 
    void printInfo() {
        System.out.println(is);
    }
}
 
public class TransDemo {
    public static void main(String[] args) throws IOException {
        if (args.length != 1) {
            System.err.println("usage: java TransDemo classfile");
            return;
        }
        TestClass cl = new TestClass(new FileInputStream(args[0]));
        System.out.printf("Minor version number: %d%n", cl.getMinorVer());
        System.out.printf("Major version number: %d%n", cl.getMajorVer());
        cl.printInfo();
 
        try (FileOutputStream fos = new FileOutputStream("test.file");
                ObjectOutputStream oos = new ObjectOutputStream(fos)) {
            oos.writeObject(cl);
        }
 
        cl = null;
 
        try (FileInputStream fis = new FileInputStream("test.file");
                ObjectInputStream ois = new ObjectInputStream(fis)) {
            System.out.println();
            cl = (TestClass) ois.readObject();
            System.out.printf("Minor version number: %d%n", cl.getMinorVer());
            System.out.printf("Major version number: %d%n", cl.getMajorVer());
            cl.printInfo();
        } catch (ClassNotFoundException cnfe) {
            System.err.println(cnfe.getMessage());
        }
    }
}
相关阅读:
java中transient关键字具有什么功能呢?
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaJingYan/202210/16653214354596.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者