import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import org.apache.commons.codec.binary.Base64;
public class Utils {
public static <T extends Serializable> T string2Object(String objBody, Class<T> bean) {
if (objBody == null || objBody.length() == 0)
return null;
T result = null;
ByteArrayInputStream bais = null;
ObjectInputStream oin = null;
try {
bais = new ByteArrayInputStream(new Base64().decode(objBody));
oin = new ObjectInputStream(bais);
result = (T) oin.readObject();
} catch (IOException e) {
} catch (ClassNotFoundException e) {
} finally {
try {
oin.close();
bais.close();
} catch (IOException e) {
}
}
return result;
}
public static <T extends Serializable> String object2String(T value) {
if (value == null)
return null;
String result = null;
ByteArrayOutputStream baos = null;
ObjectOutputStream oos = null;
try {
baos = new ByteArrayOutputStream(4096);
oos = new ObjectOutputStream(baos);
oos.writeObject(value);
oos.flush();
result = new String(new Base64().encode(baos.toByteArray()));
} catch (IOException e) {
} finally {
try {
oos.close();
baos.close();
} catch (IOException e) {
}
}
return result;
}
}
Java序列化与反序列化对象方法
最新推荐文章于 2025-03-08 09:55:11 发布
本文介绍了一个实用的Java工具类,用于实现对象的序列化与反序列化操作。该工具类支持将Java对象转换为Base64编码的字符串或将此类字符串还原为原始Java对象,适用于网络传输或持久化存储等场景。
3162

被折叠的 条评论
为什么被折叠?



