Java 版本序列化
Player
package com.john.netty.learn.ch07.java;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Player implements java.io.Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private long playerId;
private String name;
private int age;
private List<Integer> skills;
public Player(long playerId, String name, int age) {
this.playerId = playerId;
this.name = name;
this.age = age;
skills = new ArrayList<>();
}
public long getPlayerId() {
return playerId;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public List<Integer> getSkills() {
return skills;
}
public void addSkill(int skill) {
skills.add(skill);
}
@Override
public String toString() {
return "playerId:" +playerId +" name:" + name +" age:" + this.age +" skills:" + Arrays.toString(this.skills.toArray(new Integer[this.skills.size()]));
}
}
Java2Bytes: 通过ObjectOutputStream 序列化对象
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
这里再给大家普及一个知识:
为什么实现Serializable方法,最好提供serialVersionUID 数值呢?
例如: private static final long serialVersionUID = 1L; 数值不重要
如果我们不提供serialVersionUID static 变量,那么 一旦对象变更,例如Player 增加 address 字段,
原来Player将无法支持反序列化这个新的Player对象序列化的值,尽管我们可以将新的address 可以设置为null,当由于Player变更了,serialVersionUID 由JVM 生成,数值变化了,导致反序列化失败,如何避免呢?通过提供serialVersionUID数值即可。
Old Player 序列化对象 -网络传输到Server端-》New Player 可以反序列化,由于serialVersionUID数值没有变化, 通过新增的address 字段将会赋值为Null。
package com.john.netty.learn.ch07.java;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Arrays;
public class Java2Bytes {
public Java2Bytes() {
}
public static void main(String[] args) throws Exception {
Player player = new Player(1l, "John Hao", 12);
player.addSkill(1001);
player.addSkill(1002);
player.addSkill(1003);
byte[] bytes = toBytes(player);
System.out.println(Arrays.toString(bytes));
System.out.println(toObject(Player.class, bytes));
}
public static <T> T toObject(Class<T> clz, byte[] bytes) throws Exception {
ByteArrayInputStream is = new ByteArrayInputStream(bytes);
ObjectInputStream objectInputStream = new ObjectInputStream(is);
Object obj = objectInputStream.readObject();
objectInputStream.close();
is.close();
return (T) obj;
}
public static byte[] toBytes(Object bean) throws IOException {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
objectOutputStream.writeObject(bean);
objectOutputStream.flush();
objectOutputStream.close();
return byteArrayOutputStream.toByteArray();
}
}
Java结果: 与Protobuff 相比, 非常大的字节流,即占用更多的带宽及反序列化也将占用更多的资源
所有源码下载 :https://download.csdn.net/download/netcobol/10308871