50,331
社区成员




public class A {
Object C;
public Object getC() {
return C;
}
public void setC(Object c) {
C = c;
}
public static void main(String[] args) {
B b = new B();
A a=new A();
a.setC(b);
B bb=(B)a.getC();
System.out.println("print A-B-List before serialize");
for (int i = 0; i < bb.getList().size(); i++) {
System.out.println("list["+i+"]="+bb.getList().get(i));
}
byte[] test=SerializationUtil.serialize(a);
A newA=SerializationUtil.deserialize(test, A.class);
bb=(B)newA.getC();
System.out.println("print A-B-List after serialize");
for (int i = 0; i < bb.getList().size(); i++) {
System.out.println("list["+i+"]="+bb.getList().get(i));
}
System.out.println();
}
}
public class B {
private int num;
private String str;
private List<String> list;
public B() {
num = 3;
str = "rpc";
list = new ArrayList<String>();
list.add("rpc-list");
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public String getStr() {
return str;
}
public void setStr(String str) {
this.str = str;
}
public List<String> getList() {
return list;
}
public void setList(List<String> list) {
this.list = list;
}
}
public class SerializationUtil {
private static Map<Class<?>, Schema<?>> cachedSchema = new ConcurrentHashMap<Class<?>, Schema<?>>();
private static Objenesis objenesis = new ObjenesisStd(true);
private SerializationUtil() {
}
@SuppressWarnings("unchecked")
private static <T> Schema<T> getSchema(Class<T> cls) {
Schema<T> schema = (Schema<T>) cachedSchema.get(cls);
if (schema == null) {
schema = RuntimeSchema.createFrom(cls);
if (schema != null) {
cachedSchema.put(cls, schema);
}
}
return schema;
}
/**
* 序列化(对象 -> 字节数组)
*/
@SuppressWarnings("unchecked")
public static <T> byte[] serialize(T obj) {
Class<T> cls = (Class<T>) obj.getClass();
LinkedBuffer buffer = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE);
try {
Schema<T> schema = getSchema(cls);
return ProtostuffIOUtil.toByteArray(obj, schema, buffer);
} catch (Exception e) {
throw new IllegalStateException(e.getMessage(), e);
} finally {
buffer.clear();
}
}
/**
* 反序列化(字节数组 -> 对象)
*/
public static <T> T deserialize(byte[] data, Class<T> cls) {
try {
T message = (T) objenesis.newInstance(cls);
Schema<T> schema = getSchema(cls);
ProtostuffIOUtil.mergeFrom(data, message, schema);
return message;
} catch (Exception e) {
throw new IllegalStateException(e.getMessage(), e);
}
}
}
<!-- Protostuff -->
<dependency>
<groupId>com.dyuproject.protostuff</groupId>
<artifactId>protostuff-core</artifactId>
<version>1.0.7</version>
</dependency>
<dependency>
<groupId>com.dyuproject.protostuff</groupId>
<artifactId>protostuff-runtime</artifactId>
<version>1.0.7</version>
</dependency>