android 序列化

?





1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

200

201

202

203

204

205

206

207

208

209

210

211

212

213

214

215

216

217

218

219

220

221

222

223

224

225

226

227

228

229

230

231

232

233

234

235

236

237

238

239

240

241

242

243

244

245

246

247

248

249

250

251

252

253

254

255

256

257

258

259

260

261

262

263

264

package
com.yunkapay.push.mobile.parcelable;

import android.os.Parcel;

import android.os.Parcelable;

import android.util.Log;

import com.yunkapay.push.mobile.util.Logger;

import java.lang.reflect.*;

import
java.util.*;

public
abstract class GlobalParcelable<T extends
GlobalParcelable> implements
Parcelable {

    public
GlobalParcelable() {

        // TODO Auto-generated constructor stub

    }

    public
GlobalParcelable(Parcel in) {

        String className = in.readString();

        Log.i("GlobalParcelable", "Constructor: "
+ ((Object) this).getClass().getSimpleName() + "; In parcel: "
+ className);

        readFromParcel(in);

    }

    @Override

    public
void writeToParcel(Parcel dest, int
flags) {

        dest.writeString(((Object) this).getClass().getName());

        try
{

            dehydrate(this, dest);

        } catch
(IllegalArgumentException e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

        } catch
(IllegalAccessException e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

        }

    }

    public
void readFromParcel(Parcel in) {

        try
{

            rehydrate(this, in);

        } catch
(IllegalArgumentException e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

        } catch
(IllegalAccessException e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

        }

    }

    @Override

    public
int describeContents() {

        // TODO Auto-generated method stub

        return
0;

    }

    // writes fields of a GlobalParcelable to a parcel

    // does not include the first parcelled item -- the class name

    protected
void dehydrate(GlobalParcelable model, Parcel out) throws
IllegalArgumentException, IllegalAccessException {

        Class<?> cla = ((Object) model).getClass();

        Log.i("GlobalParcelable", "dehydrating... "
+ cla.toString());

        // get the fields

        Field[] fields=getFields(cla);

        // sort the fields so it is in deterministic order

        Arrays.sort(fields, compareMemberByName);

        // populate the fields

        for
(Field field : fields) {

            field.setAccessible(true);

            int
modifier = field.getModifiers();

            Log.i("GlobalParcelable", "Field:"
+ field.getName() + " "
+ Modifier.isStatic(modifier) + " "
+ Modifier.isFinal(modifier));

            if
(field.getType().equals(int.class)) {

                out.writeInt(field.getInt(model));

            } else
if (field.getType().equals(double.class)) {

                out.writeDouble(field.getDouble(model));

            } else
if (field.getType().equals(float.class)) {

                out.writeFloat(field.getFloat(model));

            } else
if (field.getType().equals(long.class)) {

                out.writeLong(field.getLong(model));

            } else
if (field.getType().equals(String.class)) {

                out.writeString((String) field.get(model));

            } else
if (field.getType().equals(boolean.class)) {

                out.writeByte(field.getBoolean(model) ? (byte) 1
: (byte) 0);

            } else
if (field.getType().equals(Date.class)) {

                Date date = (Date) field.get(model);

                if
(date != null) {

                    out.writeLong(date.getTime());

                } else
{

                    out.writeLong(0);

                }

            } else
if (GlobalParcelable.class.isAssignableFrom(field.getType())) {

                // why did this happen?

                Log.e("GlobalParcelable", "GlobalParcelable F*ck up: "
+ " (" + field.getType().toString() + ")");

                out.writeParcelable((GlobalParcelable) field.get(model), 0);

            } else
{

                // wtf

                Log.e("GlobalParcelable", "Could not write field to parcel: "
+ " (" + field.getType().toString() + ")");

            }

        }

    }

    protected
static Field[] getFields(Class<?> cla) {

        List<Field> fieldList = new
ArrayList<Field>();

        do
{

            Logger.d("Class "+cla.toString());

            Field[] fields = cla.getDeclaredFields();

            for
(Field f : fields) {

                int
modifier = f.getModifiers();

                if
(Modifier.isStatic(modifier) && Modifier.isFinal(modifier)) {

                    Logger.d("final static value "+f.getName());

                } else
{

                    fieldList.add(f);

                }

            }

            cla = cla.getSuperclass();

        } while
(cla != null
&& !GlobalParcelable.class.equals(cla));

        return
fieldList.toArray(new
Field[fieldList.size()]);

    }

    // reads the parcelled items and put them into this object‘s fields

    // must be run after getting the first parcelled item -- the class name

    protected
static void rehydrate(GlobalParcelable model, Parcel in) throws
IllegalArgumentException, IllegalAccessException {

        Class<?> cla = ((Object) model).getClass();

        Log.i("GlobalParcelable", "rehydrating... "
+ cla.toString());

        // get the fields

        Field[] fields =getFields(cla);

        // sort the fields so it is in deterministic order

        Arrays.sort(fields, compareMemberByName);

        // populate the fields

        for
(Field field : fields) {

            field.setAccessible(true);

            if
(field.getType().equals(int.class)) {

                field.set(model, in.readInt());

            } else
if (field.getType().equals(double.class)) {

                field.set(model, in.readDouble());

            } else
if (field.getType().equals(float.class)) {

                field.set(model, in.readFloat());

            } else
if (field.getType().equals(long.class)) {

                field.set(model, in.readLong());

            } else
if (field.getType().equals(String.class)) {

                field.set(model, in.readString());

            } else
if (field.getType().equals(boolean.class)) {

                field.set(model, in.readByte() == 1);

            } else
if (field.getType().equals(Date.class)) {

                Date date = new
Date(in.readLong());

                field.set(model, date);

            } else
if (GlobalParcelable.class.isAssignableFrom(field.getType())) {

                Log.e("GlobalParcelable", "read GlobalParcelable: "
+ " (" + field.getType().toString() + ")");

                field.set(model, in.readParcelable(field.getType().getClassLoader()));

            } else
{

                // wtf

                Log.e("GlobalParcelable", "Could not read field from parcel: "
+ field.getName() + " ("
+ field.getType().toString() + ")");

            }

        }

    }

    /*

     * Comparator object for Members, Fields, and Methods

     */

    private
static Comparator<Field> compareMemberByName =

            new
CompareMemberByName();

    private
static class CompareMemberByName implements
Comparator {

        public
int compare(Object o1, Object o2) {

            String s1 = ((Member) o1).getName();

            String s2 = ((Member) o2).getName();

            if
(o1 instanceof
Method) {

                s1 += getSignature((Method) o1);

                s2 += getSignature((Method) o2);

            } else
if (o1 instanceof
Constructor) {

                s1 += getSignature((Constructor) o1);

                s2 += getSignature((Constructor) o2);

            }

            return
s1.compareTo(s2);

        }

    }

    /**

     * Compute the JVM signature for the class.

     */

    private
static String getSignature(Class clazz) {

        String type = null;

        if
(clazz.isArray()) {

            Class cl = clazz;

            int
dimensions = 0;

            while
(cl.isArray()) {

                dimensions++;

                cl = cl.getComponentType();

            }

            StringBuffer sb = new
StringBuffer();

            for
(int i = 0; i < dimensions; i++) {

                sb.append("[");

            }

            sb.append(getSignature(cl));

            type = sb.toString();

        } else
if (clazz.isPrimitive()) {

            if
(clazz == Integer.TYPE) {

                type = "I";

            } else
if (clazz == Byte.TYPE) {

                type = "B";

            } else
if (clazz == Long.TYPE) {

                type = "J";

            } else
if (clazz == Float.TYPE) {

                type = "F";

            } else
if (clazz == Double.TYPE) {

                type = "D";

            } else
if (clazz == Short.TYPE) {

                type = "S";

            } else
if (clazz == Character.TYPE) {

                type = "C";

            } else
if (clazz == Boolean.TYPE) {

                type = "Z";

            } else
if (clazz == Void.TYPE) {

                type = "V";

            }

        } else
{

            type = "L"
+ clazz.getName().replace(‘.‘, ‘/‘) + ";";

        }

        return
type;

    }

    /*

     * Compute the JVM method descriptor for the method.

     */

    private
static String getSignature(Method meth) {

        StringBuffer sb = new
StringBuffer();

        sb.append("(");

        Class[] params = meth.getParameterTypes(); // avoid clone

        for
(int j = 0; j < params.length; j++) {

            sb.append(getSignature(params[j]));

        }

        sb.append(")");

        sb.append(getSignature(meth.getReturnType()));

        return
sb.toString();

    }

    /*

     * Compute the JVM constructor descriptor for the constructor.

     */

    private
static String getSignature(Constructor cons) {

        StringBuffer sb = new
StringBuffer();

        sb.append("(");

        Class[] params = cons.getParameterTypes(); // avoid clone

        for
(int j = 0; j < params.length; j++) {

            sb.append(getSignature(params[j]));

        }

        sb.append(")V");

        return
sb.toString();

    }

}

  

?





1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

package
com.yunkapay.push.mobile.notification;

import android.os.Parcel;

import android.os.Parcelable;

import com.yunkapay.push.mobile.parcelable.GlobalParcelable;

import com.yunkapay.push.mobile.util.Logger;

import org.json.JSONObject;

/**

 * Created with IntelliJ IDEA.

 * User: zac

 * Date: 12/2/13

 * Time: 2:26 PM

 * To change this template use File | Settings | File Templates.

 */

public
class XJNotification extends
GlobalParcelable {

    public
static final String ELEMENT_NAME = "notification";

    public
static final String NAMESPACE = "pubsub:message:notification";

    public
static final String NOTIFICATION_NODE = "node";

    public
static final String NOTIFICATION_ID = "id";

    public
static final String NOTIFICATION_TITLE = "title";

    public
static final String NOTIFICATION_CONTENT = "content";

    public
static final String NOTIFICATION_TYPE = "type";

    public
static final String NOTIFICATION_IMAGE_URL = "image_url";

    public
static final String NOTIFICATION_LINK = "link";

    public
static final String NOTIFICATION_TIME = "time";

    public
static final String NOTIFICATION_TIME_TO_LIVE = "time_to_live";

    public
String mNotificationID;

    public
String mNode;

    public
String mTitle;

    public
String mContent;

    public
long mTime;

    public
int mTimeToLive;

    public
XJNotification(JSONObject jsonObject) {

    }

    public
XJNotification() {

        super();

    }

    public
static final Parcelable.Creator<XJNotification> CREATOR = new
Parcelable.Creator<XJNotification>() {

        public
XJNotification createFromParcel(Parcel in) {

            // get class from first parcelled item

            Class<?> parceledClass;

            try
{

                parceledClass = Class.forName(in.readString());

                Logger.i("Creator: "
+ parceledClass.getSimpleName());

                // create instance of that class

                XJNotification model = (XJNotification) parceledClass.newInstance();

                rehydrate(model, in);

                return
model;

            } catch
(ClassNotFoundException e) {

                // TODO Auto-generated catch block

                e.printStackTrace();

            } catch
(InstantiationException e) {

                // TODO Auto-generated catch block

                e.printStackTrace();

            } catch
(IllegalAccessException e) {

                // TODO Auto-generated catch block

                e.printStackTrace();

            }

            return
null;

        }

        public
XJNotification[] newArray(int
size) {

            return
new XJNotification[size];

        }

    };

    public
String getNotificationID() {

        return
this.mNotificationID;

    }

    public
String getNode() {

        return
this.mNode;

    }

    public
String getTitle() {

        return
this.mTitle;

    }

    public
String getContent() {

        return
this.mContent;

    }

    public
static String getElementName() {

        return
ELEMENT_NAME;

    }

    public
long getTime() {

        return
this.mTime;

    }

    public
int getTimeToLive() {

        return
this.mTimeToLive;

    }

    public
void setNotificationID(String notificationID) {

        this.mNotificationID = notificationID;

    }

    public
void setNode(String node) {

        this.mNode = node;

    }

    public
void setTitle(String title) {

        this.mTitle = title;

    }

    public
void setContent(String content) {

        this.mContent = content;

    }

    public
void setTime(long
time) {

        this.mTime = time;

    }

    public
void setTimeToLive(int
timeToLive) {

        this.mTimeToLive = timeToLive;

    }

    public
NotificationType getType() {

        return
NotificationType.UNKNOWN;

    }

}

  

时间: 2024-08-07 08:23:52

android 序列化的相关文章

Android序列化

序列化介绍: 一.序列化.反序列化是什么? (1) 名词解释 对象的序列化 : 把Java对象转换为字节序列并存储至一个储存媒介的过程.对象的反序列化:把字节序列恢复为Java对象的过程. (2) 序列化详细解释 对象的序列化涉及三个点关键点:Java对象.字节序列.存储. 1. Java对象的组成?Java对象包含变量与方法.但是序列与反序列化仅处理Java变量而不处理方法,序列与反序列化仅对数据进行处理. 2. 什么是字符序列?字符序列是两个词,字符是在计算机和电信领域中,字符(Charac

Android 序列化对象接口Parcelable使用方法

什么是Parcelable ? Parcelable,定义了将数据写入Parcel,和从Parcel中读出的接口.一个实体(用类来表示),如果需要封装到消息中去,就必须实现这一接口,实现了这一接口,该实体就成为"可打包的"了. Parcelable 传递对象 Android序列化对象主要有两种方法: 1.实现Serializable接口,实现Serializable接口是JavaSE本身就支持的; 2.实现Parcelable接口,Parcelable是Android特有的功能,效率比

Android开发之漫漫长途 X——Android序列化

该文章是一个系列文章,是本人在Android开发的漫漫长途上的一点感想和记录,我会尽量按照先易后难的顺序进行编写该系列.该系列引用了<Android开发艺术探索>以及<深入理解Android 卷Ⅰ,Ⅱ,Ⅲ>中的相关知识,另外也借鉴了其他的优质博客,在此向各位大神表示感谢,膜拜!!!另外,本系列文章知识可能需要有一定Android开发基础和项目经验的同学才能更好理解,也就是说该系列文章面向的是Android中高级开发工程师. 前言 上一篇中我们比较详尽的分析了ServiceManag

Android 序列化比对

本文转自:https://www.zybuluo.com/linux1s1s/note/91046 注:部分内容有更改 在Android中使用序列化,无非两种途经: Parcelable 和 Serializable 两者区别 Serializable的作用是为了保存对象的属性到本地文件.数据库.网络流.rmi以方便数据传输,当然这种传输可以是程序内的也可以是两个程序间的. Parcelable的设计初衷是因为Serializable效率过慢,为了在程序内不同组件间以及不同Android程序间(

Android 序列化 反序列功能

1 /** 2 * 序列化对象 3 * 4 * @return 序列化后的字符串 5 */ 6 private String serializeObject(Object object) { 7 ByteArrayOutputStream byteArrayOutputStream=null; 8 ObjectOutputStream objectOutputStream=null; 9 String serStr=""; 10 try{ 11 byteArrayOutputStrea

(转)Android 序列化对象接口Parcelable使用方法

http://blog.csdn.net/zpf8861/article/details/39400725

Android Parcelable接口的使用/序列化数据

首先,我们要知道Android序列化的方法有两种,一个是实现Serializable,这是JavaSE中就支持的接口,后来google推出了专门针对Android的接口Parcelable(其性能相对Serializable将近快了10倍) 然后我们要知道Android内部传递实例的基本方法:一是Bundle.putSerializable(Key,Object),另一种是Bundle.putParcelable(Key,Object),它们分别要实现Serializable和Parcelabl

android对象序列化Parcelable浅析

一.android序列化简介 我们已经知道在Android使用Intent/Bindler进行IPC传输数据时,需要将对象进行序列化. JAVA原本已经提供了Serializable接口来实现序列化,使用起来非常简单,主要用于对象持久化以及对象的网络传输.Serializable开销比较大,因为序列化和反序列化的过程需要大量的I/O操作. Android提供了Parcelable对象序列化操作是内存序列化,主要用于Intent/Bindler的IPC数据传输. 二.Parcelable序列化使用

android 混淆 与 反编译

1, 文件 project.properties 修改: target=android-14proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt 必须这个顺序. 2,proguard-project.txt 注意排除使用反射的源码. # To enable ProGuard in your project, edit project.properties# to define the