1.使用ByteArrayStream 和 ObjectStream
public abstract class ByteConvert {
public byte[] getByte(){
try ( ByteArrayOutputStream out =new ByteArrayOutputStream();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(out)) {
objectOutputStream.writeObject(this);
objectOutputStream.flush();
return out.toByteArray();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public <T extends ByteUtil> T getObject(byte[] bytes){
try(
ByteArrayInputStream byteInputStream = new ByteArrayInputStream(bytes);
ObjectInputStream b = new ObjectInputStream(byteInputStream)) {
return (T) b.readObject();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return null ;
}
2.使用proto
public abstract class ByteConvert {
public byte[] getByte(){
return ProtostuffUtils.serialize(this);
}
public <T extends ByteUtil> T getObject(byte[] bytes){
return (T) ProtostuffUtils.deserialize(bytes,this.getClass());
}
}
ProtostuffUtils
- 引入pom
<!--引入protostuff依賴-->
<dependency>
<groupId>io.protostuff</groupId>
<artifactId>protostuff-core</artifactId>
<version>1.6.0</version>
</dependency>
<dependency>
<groupId>io.protostuff</groupId>
<artifactId>protostuff-runtime</artifactId>
<version>1.6.0</version>
</dependency>
2.編寫工具類
public class ProtostuffUtils {
/**
* 避免每次序列化都重新申請(qǐng)Buffer空間
*/
private static LinkedBuffer buffer = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE);
/**
* 緩存Schema
*/
private static Map<Class<?>, Schema<?>> schemaCache = new ConcurrentHashMap<>();
/**
* 序列化方法匹颤,把指定對(duì)象序列化成字節(jié)數(shù)組
*
* @param obj
* @param <T>
* @return
*/
@SuppressWarnings("unchecked")
public static <T> byte[] serialize(T obj) {
Class<T> clazz = (Class<T>) obj.getClass();
Schema<T> schema = getSchema(clazz);
byte[] data;
try {
data = ProtostuffIOUtil.toByteArray(obj, schema, buffer);
} finally {
buffer.clear();
}
return data;
}
/**
* 反序列化方法滥比,將字節(jié)數(shù)組反序列化成指定Class類型
*
* @param data
* @param clazz
* @param <T>
* @return
*/
public static <T> T deserialize(byte[] data, Class<T> clazz) {
Schema<T> schema = getSchema(clazz);
T obj = schema.newMessage();
ProtostuffIOUtil.mergeFrom(data, obj, schema);
return obj;
}
@SuppressWarnings("unchecked")
private static <T> Schema<T> getSchema(Class<T> clazz) {
Schema<T> schema = (Schema<T>) schemaCache.get(clazz);
if (Objects.isNull(schema)) {
//這個(gè)schema通過RuntimeSchema進(jìn)行懶創(chuàng)建并緩存
//所以可以一直調(diào)用RuntimeSchema.getSchema(),這個(gè)方法是線程安全的
schema = RuntimeSchema.getSchema(clazz);
if (Objects.nonNull(schema)) {
schemaCache.put(clazz, schema);
}
}
return schema;
}
}