码迷,mamicode.com
首页 > 编程语言 > 详细

Java中transient有何作用?

时间:2015-04-07 21:24:18      阅读:226      评论:0      收藏:0      [点我收藏+]

标签:

  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+"\n");
		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

 

Java中transient有何作用?

标签:

原文地址:http://www.cnblogs.com/luankun0214/p/4399350.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!