Created
March 22, 2018 01:52
-
-
Save zhanggang807/2d61b7ea547368b8f143556681592d47 to your computer and use it in GitHub Desktop.
java Externalizable interface demo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.*; | |
/** | |
* reference link | |
* https://mp.weixin.qq.com/s/QS9e_lVxr5vuphql5O3xhA | |
* https://www.cnblogs.com/chenfei0801/archive/2013/04/06/3002146.html | |
* 对一个实现了Externalizable接口的类进行序列化及反序列化 | |
*/ | |
public class ExternalizableDemo1 { | |
public static void main(String[] args) { | |
//Write Obj to file | |
User1 user = new User1(); | |
user.setName("hollis"); | |
user.setAge(23); | |
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("tempFile"))) { | |
oos.writeObject(user); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
//Read Obj from file | |
File file = new File("tempFile"); | |
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file))) { | |
User1 newInstance = (User1) ois.readObject(); | |
//output | |
System.out.println(newInstance); | |
} catch (IOException | ClassNotFoundException e) { | |
e.printStackTrace(); | |
} | |
} | |
} | |
//OutPut: | |
//User{name='null', age=0} | |
//在writeExternal readExternal 写入相关代码后发现有值了 | |
//我觉得write 和 read 必须按顺序来,什么顺序write 就什么顺序 read | |
//Externalizable这个可以控制某些字段序列化时不输入值,或者某些字段可以输出值,也可以使用 transient 关键字来实现 | |
//Externalizable 相比 Serializable接口更加的可控,更加的灵活 | |
class User1 implements Externalizable { | |
private String name; | |
private int 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; | |
} | |
public void writeExternal(ObjectOutput out) throws IOException { | |
System.out.println("invoke writeExtenal???"); | |
out.writeObject(name);//原本是不输入值的,加了这个之后读时就会读出来, | |
out.writeInt(age); | |
} | |
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { | |
System.out.println("invoke readExtenal???"); | |
name = (String) in.readObject();// 原本是不输出值的,现在有值了 | |
age = in.readInt(); | |
} | |
public User1() { | |
} | |
@Override | |
public String toString() { | |
return "User{" + | |
"name='" + name + '\'' + | |
", age=" + age + | |
'}'; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment