美文网首页
序列化Serializable和Parcelable

序列化Serializable和Parcelable

作者: 荞麦穗 | 来源:发表于2017-11-14 16:36 被阅读0次

    序列化主要有两种方式:Serializable,Parcelable;
    区别:
    内存的序列化Parcelable(直接读取内存,效率高,使用略麻烦)
    序列化到本地存储设备或序列化后通过网络传输使用Serializable
    优缺点:
    Parcelable:直接读取内存,效率高,使用略麻。
    Serializable:使用简单,开销大,(序列化过程会产生大量的I/O操作)
    class序列化
    Serializable

    public class User implements Serializable {
        private static final long serialVersionUID=1L;
    
        public int userId;
        public String userName;
        public boolean isMale;
    }
    
    User n = new User();
    Intent i = new Intent(A.this, B.class);
    i.putExtra("User", u);
    startActivity(i);    
    
    User u = (User)getIntent().getSerializableExtra("User");  
    

    Parcelable

    public class User implements Parcelable {
    
        public int userId;
        public String userName;
        public boolean isMale;
        
        @Override
        public int describeContents() {
            return 0;
        }
        /**
        *序列化
        */
        @Override
        public void writeToParcel(Parcel dest, int flags) {
            dest.writeInt(userId);
            dest.writeString(userName);
            dest.writeInt(isMale?1:0);
        }
        /**
         * 反序列化
         */
        public static final Parcelable.Creator<User> CREATOR = new Creator<User>() {
            @Override
            public User createFromParcel(Parcel source) {
                return new User(source);
            }
    
            @Override
            public User[] newArray(int size) {
                return new User[size];
            }
        };
        private User(Parcel source){
            userId = source.readInt();
            userName = source.readString();
            isMale = source.readInt() == 1;
        }
    }
    
    
    Intent intent = new Intent(A.this,B.class);  
    Bundle mBundle = new Bundle();  
    mBundle.putParcelable("User", u);  
    intent.putExtras(mBundle);  
    startActivity(intent);  
    
    User u= (User)getIntent().getParcelableExtra("User"); 
    

    对象的序列化

            File file = new File("person.out");  
            ObjectOutputStream oout = new ObjectOutputStream(new FileOutputStream(file));  
            Person person = new Person("John", 101, Gender.MALE);  
            oout.writeObject(person);  
            oout.close();  
     
            ObjectInputStream oin = new ObjectInputStream(new FileInputStream(file));  
            Object newPerson = oin.readObject(); // 没有强制转换到Person类型  
            oin.close();  
    
    使用Android Studio插件序列化

    安卓插件
    File -> Settings -> Pugins -> Browse Repositories 如下,输入android parcelable code generator
    Mac OS control+enter


    屏幕快照 2018-03-09 下午6.45.08.png

    相关文章

      网友评论

          本文标题:序列化Serializable和Parcelable

          本文链接:https://www.haomeiwen.com/subject/firfvxtx.html