自己写的java序列化,版本0.2(依赖于java反射机制)
luyued 发布于 2011-04-15 01:36 浏览 N 次0.2
更新内容
1.修改序列化规则,采用{}成对方式标志对象,并对关键字符如 '{' ,'}','\r', '\n','='进行转义
2.支持Map中键值对都为对象的功能
源代码:
----------------------------------SerializableUtil ---------------------------------------------------------------------------
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.util.List;
import java.util.Map;
@SuppressWarnings("unchecked")
public class SerializableUtil {
public static String serializable(Object obj)
{
if(obj==null)return "{null}";
Class clazz=obj.getClass();
String type=clazz.getName();
String re="";
if(ObjectUtil.isBaseType(type))
{
re+=save(type,obj);
}
else if(ObjectUtil.isArray(type))
{
re+="{"+type+":";
re+=serializableArray(obj);
re+="}";
}
else if(ObjectUtil.isList(type))
{
re+="{"+type+":";
re+=serializableList((List)obj);
re+="}";
}
else if(ObjectUtil.isMap(type))
{
re+="{"+type+":";
re+=serializableMap((Map)obj);
re+="}";
}
else
{
re+="{"+type+":";
re+=serializableObject(obj);
re+="}";
}
return re;
}
private static String save(String type, Object obj)
{
String re="{";
if("java.lang.Integer".equals(type)||"int".equals(type))
{
re+="int:";
re+=obj.toString();
}
else if("java.lang.Boolean".equals(type)||"boolean".equals(type))
{
re+="boolean:";
re+=obj.toString();
}
else if("java.lang.Byte".equals(type)||"byte".equals(type))
{
re+="byte:";
re+=obj.toString();
}
else if("java.lang.Double".equals(type)||"double".equals(type))
{
re+="double:";
re+=obj.toString();
}
else if("java.lang.Short".equals(type)||"short".equals(type))
{
re+="short:";
re+=obj.toString();
}
else if("java.lang.Long".equals(type)||"long".equals(type))
{
re+="long:";
re+=obj.toString();
}
else if("java.lang.Float".equals(type)||"float".equals(type))
{
re+="float:";
re+=obj.toString();
}
else
{
re+="string:";
re+=obj.toString().replaceAll("%","%").replaceAll("\\{","{").replaceAll("\\}","}").replaceAll("=", "=");
}
return re+"}";
}
private static String serializableArray(Object obj)
{
String re="";
int len=Array.getLength(obj);
for(int i=0;i
Object tmp=ObjectUtil.getArrayElement(obj, i);
re+=serializable(tmp);
}
return re;
}
private static String serializableMap(Map map) {
String re="";
for(Object key:map.keySet())
{
String k=serializable(key);
String v=serializable(map.get(key));
re+="{"+k+"="+v+"}";
}
return re;
}
private static String serializableList(List list){
String re="";
for(int i=0;i
Object tmp=list.get(i);
re+=serializable(tmp);
}
return re;
}
private static String serializableObject(Object obj) {
String re="";
if(obj==null)return null;
List
if(fields==null)return null;
for(Field field:fields)
{
String fieldName=field.getName();
Object value=ObjectUtil.getValue(field,obj);
re+="{\""+fieldName+"\":"+serializable(value)+"}";
}
return re;
}
}
----------------------------------DeserializableUtil ---------------------------------------------------------------------------
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@SuppressWarnings("unchecked")
public class DeserializableUtil {
public static Object deserializable(String src)
{
Object obj=null;
if(src.length()<3)return null;
src=src.substring(1,src.length()-1);
String type=null,value=null;
String params[]=src.split(":",2);
if(params.length<2)
{
value="";
}
else
{
value=params[1];
}
if(value==null||"{null}".equals(value))
{
return null;
}
type=params[0];
if(ObjectUtil.isBaseType(type))
{
obj=retrive(type,value);
}
else if(ObjectUtil.isArray(type))
{
Class clazz=ObjectUtil.getArrayType(type);
obj=deserializableArray(value,clazz);
}
else if(ObjectUtil.isList(type))
{
obj=deserializableList(value,type);
}
else if(ObjectUtil.isMap(type))
{
obj=deserializableMap(value,type);
}
else
{
obj=deserializableObject(value,type);
}
return obj;
}
private static Object retrive(String type, String value)
{
Object obj=null;
if("java.lang.Integer".equals(type)||"int".equals(type))
{
if("".equals(value))value="0";
obj=Integer.parseInt(value);
}
else if("java.lang.Boolean".equals(type)||"boolean".equals(type))
{
if("".equals(value))value="0";
if("".equals(value))value="false";
obj=Boolean.parseBoolean(value);
}
else if("java.lang.Byte".equals(type)||"byte".equals(type))
{
if("".equals(value))value="0";
obj=Byte.parseByte(value);
}
else if("java.lang.Double".equals(type)||"double".equals(type))
{
if("".equals(value))value="0";
obj=Double.parseDouble(value);
}
else if("java.lang.Short".equals(type)||"short".equals(type))
{
if("".equals(value))value="0";
obj=Short.parseShort(value);
}
else if("java.lang.Long".equals(type)||"long".equals(type))
{
if("".equals(value))value="0";
obj=Long.parseLong(value);
}
else if("java.lang.Float".equals(type)||"float".equals(type))
{
if("".equals(value))value="0";
obj=Float.parseFloat(value);
}
else
{
obj=value.replaceAll("%","%").replaceAll("{","{").replaceAll("}","}").replaceAll("=", "=");
}
return obj;
}
private static Object deserializableArray(String src,Class clazz)
{
List list=null;
if(src.length()<1)return null;
list=new ArrayList();
int end=-1;
for(int i=0;i
end=getDest(i,src);
if(end==-1)
{
break;
}
String sub=src.substring(i,end+1);
Object tmp=deserializable(sub);
list.add(tmp);
if(end==src.length()-1)
{
break;
}
i=end+1;
}
Object array=ObjectUtil.newArray(clazz,list.size());
for(int i=0;i
ObjectUtil.putArrayElement(array,i,list.get(i));
}
return array;
}
private static Map deserializableMap(String src,String type) {
Map map=null;
if(src.length()<1)return null;
map=(Map)ObjectUtil.getInstance(type);
int end=-1;
for(int i=0;i
end=getDest(i,src);
if(end==-1)
{
break;
}
String sub=src.substring(i+1,end);
String params[]=sub.split("=",2);
Object key=deserializable(params[0]);
Object value=null;
if(params.length>1)
{
value=deserializable(params[1]);
}
map.put(key, value);
if(end==src.length()-1)
{
break;
}
i=end+1;
}
return map;
}
private static List deserializableList(String src,String type){
List list=null;
if(src.length()<1)return null;
list=(List)ObjectUtil.getInstance(type);
int end=-1;
for(int i=0;i
end=getDest(i,src);
if(end==-1)
{
break;
}
String sub=src.substring(i,end+1);
Object tmp=deserializable(sub);
list.add(tmp);
if(end==src.length()-1)
{
break;
}
i=end+1;
}
return list;
}
private static Object deserializableObject(String src, String type) {
List
if(fields==null)return null;
Object obj=ObjectUtil.getInstance(type);
if(obj==null)return null;
int end=-1;
for(int i=0;i
end=getDest(i,src);
if(end==-1)
{
break;
}
String sub=src.substring(i+1,end);
String params[]=sub.split(":",2);
String fieldName=params[0];
String value="";
if(params.length>=2)
{
value=params[1];
}
Field field=ObjectUtil.getField(fields,fieldName);
ObjectUtil.setValue(field, obj,deserializable(value));
if(end==src.length()-1)
{
break;
}
i=end+1;
}
return obj;
}
private static int getDest(int start, String str) {
int length=str.length();
int count=-1;
int end=-1;
for(int i=start;i
char ch=str.charAt(i);
if(ch=='{')
{
++count;
}
else if(ch=='}')
{
if(count==0)
{
end=i;
break;
}
else if(count>0)
{
--count;
}
}
}
if(end==-1)
{
return end;
}
return end;
}
}
----------------------------------ObjectUtil ---------------------------------------------------------------------------
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@SuppressWarnings("unchecked")
public class ObjectUtil {
private static final String[]BASE_TYPE;
static Map
static{
BASE_TYPE=new String[]{
//"B","Z","I","L","S","D","F",
"boolean","byte","int","long","short","float","double","string",
"java.lang.Boolean","java.lang.Byte","java.lang.Integer","java.lang.Short","java.lang.Long","java.lang.Float","java.lang.Double",
"java.lang.String"
};
BASE_CLASSES.put("I",int.class);
BASE_CLASSES.put("B",byte.class);
BASE_CLASSES.put("Z",boolean.class);
BASE_CLASSES.put("D",double.class);
BASE_CLASSES.put("F",float.class);
BASE_CLASSES.put("S",short.class);
BASE_CLASSES.put("L",long.class);
}
static boolean isBaseType(String type){
for(int i=0;i
return true;
}
}
return false;
}
static boolean isMap(Class clazz){
if(Map.class.isAssignableFrom(clazz)){
return true;
}
return false;
}
static boolean isMap(String type){
try {
return isMap(Class.forName(type));
} catch (ClassNotFoundException e) {
}
return false;
}
static boolean isList(Class clazz){
if(List.class.isAssignableFrom(clazz)){
return true;
}
return false;
}
public static boolean isList(String type) {
try {
return isList(Class.forName(type));
} catch (ClassNotFoundException e) {
}
return false;
}
static boolean isArray(String type){
if(type.indexOf("[")==0)return true;
return false;
}
public static Object getInstance(String type){
Object obj=null;
try {
Class clazz=Class.forName(type);
obj=clazz.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
return obj;
}
public static
T t=null;
try {
t=clazz.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
return t;
}
static List
List
Field[] fields=null;
while(true){
fields=clazz.getDeclaredFields();
if(fields!=null){
inner:for(int i=0;i
if(serializable)
{
int modifier=field.getModifiers();
if(
Modifier.isTransient(modifier)||
Modifier.isFinal(modifier)||
Modifier.isStatic(modifier)
)
{//常量,transient,静态变量不序列化
continue inner;
}
}
field.setAccessible(true);
list.add(fields[i]);
}
}
clazz=clazz.getSuperclass();
if(clazz==null){
break;
}
}
return list;
}
static List
Class clazz=null;
try {
clazz=Class.forName(type);
} catch (ClassNotFoundException e) {
return null;
}
return getFields(clazz,serializable);
}
public static void putAllMap(Map father,Map child){
if(isNullMap(father)||isNullMap(child))return;
for(Object key:child.keySet()){
father.put(key, child.get(key));
}
}
private static boolean isNullMap(Map map){
if(map==null)return true;
return false;
}
static
if(len<=0)len=10;
Object array=Array.newInstance(clazz,len);
return array;
}
static
Array.set(array, offset, value);
}
static Object getArrayElement(Object array,int offset){
return Array.get(array,offset);
}
static
Object newArray=Array.newInstance(clazz,len);
int oldLen=Array.getLength(oldArray);
for(int i=0;i
}
return newArray;
}
public static Class getArrayType(String type){
type=type.replace("[","").replace(";","");
if(type.indexOf("L")==0){
type=type.substring(1);
}
Class clazz=null;
clazz=BASE_CLASSES.get(type);
if(clazz==null)
{
try {
clazz=Class.forName(type);
} catch (Exception e) {
e.printStackTrace();
}
}
return clazz;
}
public static void setValue(Field field,Object target,Object value)
{
if(field==null)return;
try {
field.set(target, value);
} catch (Exception e) {
e.printStackTrace();
}
}
public static Object getValue(Field field,Object target)
{
try {
return field.get(target);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static Field getField(List
{
if(fieldName.length()<3)return null;
fieldName=fieldName.substring(1,fieldName.length()-1);
for(Field field:fields)
{
if(field.getName().equals(fieldName))
{
return field;
}
}
return null;
}
}
- 06-02· 【转】 给Ubuntu安装netboo
- 06-02· Netbook
- 05-31· 你搜“联宝戏” 揭示你未
- 05-31· 联宝戏一切成功都是那么
- 05-31· 联宝(LINPO)
- 05-31· 台湾联宝CY25 ¥1400
- 05-31· 透视!笔记本奸商的无间道
- 05-31· 沈阳惠普笔记本维修千万
- 05-31· 重庆联宝活性炭恭祝各位
- 05-31· [转载]第十步:移联宝移动
- 05-28· 高端便携商务本 富士通
- 05-27· 富士通推首台器MeeGo新本
- 05-27· 富士通云计算方案三级跳
- 05-26· 惠普 Compaq 6530B(VA078PA)
- 05-26· of Alienware M14xAkku HP Compaq
- 05-26· ASUS HP COMPAQ DELL 笔记...
- 05-26· 惠普Compaq Presario CQ40 313A
- 05-25· 2011年03月25日
- 05-25· 如何安装在您的康柏Evo
- 05-25· 康柏斯校园购物网康柏斯