• Java中transient有何作用?


      transient关键字用来防止序列化域。如果一个引用类型被transient修饰,则其反序列化的结果是null。基本类型则为0。如果引用类型时不可序列化的类,则也应该使用transient修饰,它在反序列化时会被直接跳过。

    可以用transient来修饰不想保存的域

    下面的例子可以看到被transient修饰的name,使用序列化克隆后,反序列化的结果是null

    package com.lk.B;
    
    import java.io.ByteArrayInputStream;
    import java.io.ByteArrayOutputStream;
    import java.io.IOException;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    import java.io.Serializable;
    
    public class Employee implements Cloneable,Serializable{
    	private static final long serialVersionUID = 1L;
    	private transient String name;
    	private int age;
    	public Employee(String name,int age){
    		this.name = name;
    		this.age = age;
    	}
    	public String getName() {
    		return name;
    	}
    	public void setName(String name) {
    		this.name = name;
    	}
    	public int getAge() {
    		return age;
    	}
    	public void setAge(int age) {
    		this.age = age;
    	}
    	@Override
    	public String toString() {
    		// TODO Auto-generated method stub
    		StringBuffer sb = new StringBuffer();
    		sb.append("姓名:"+name+",");
    		sb.append("年龄:"+age+"
    ");
    		return sb.toString();
    	}
    	@Override
    	protected Employee clone() {
    		// TODO Auto-generated method stub
    		Employee employss = null;
    		
    		ByteArrayOutputStream baos = new ByteArrayOutputStream();
    		try {
    			ObjectOutputStream oos = new ObjectOutputStream(baos);
    			oos.writeObject(this);
    			oos.close();
    		} catch (IOException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    		
    		ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
    		try {
    			ObjectInputStream ois = new ObjectInputStream(bais);
    			employss = (Employee) ois.readObject();
    			ois.close();
    		} catch (IOException | ClassNotFoundException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    		return employss;
    	}
    }
    

      

    package com.lk.B;
    
    
    public class Test3 {
        public static void main(String[] args) {
            Employee emp = new Employee("阿坤", 21);
            System.out.println(emp);
            Employee emp1 = emp.clone();
            System.out.println(emp1);
        }
    }
    姓名:阿坤,年龄:21
    
    姓名:null,年龄:21
  • 相关阅读:
    Meterpreter
    CHM木马
    浅析ARP协议及ARP攻击
    python绝技 — 使用PyGeoIP关联IP地址和物理位置
    python虚拟环境virtualenv的安装与使用
    python调用nmap探测局域网设备
    提权
    Nexpose
    docker安装使用
    一些渗透测试练习环境介绍
  • 原文地址:https://www.cnblogs.com/luankun0214/p/4399350.html
Copyright © 2020-2023  润新知