在Activity之间传递参数(三)——serializable和parcelable的区别
传递值对象:
一、serializable实现:简单易用
serializable的迷人之处在于你只需要对某个类以及它的属性实现Serializable 接口即可。Serializable 接口是一种标识接口,这意味着无需实现方法,Java便会对这个对象进行高效的序列化操作。
这种方法的缺点是使用了反射,序列化的过程较慢。这种机制会在序列化的时候创建许多的临时对象,容易触发垃圾回收。
、新建User.java:
public class User implements Serializable{
private String name;
private int age;
public String getName() {
return name;
}
public int getAge() {
return age;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public User(String name,int age){
this.name = name;
this.age = age;
}
}
2、MainActivity.java:
i.putExtra("user",new User("Android",2));
3、TheAty.java:
User user = (User) i.getSerializableExtra("user");
tv.setText(String.format("User info(name=%s,age=%d)",user.getName(),user.getAge()));
二、Parcelable实现: 速度至上
Parcelable的实现会使代码运行地特别快:我们已经清楚地知道了序列化的过程,而不需要使用反射来推断。同时为了更快地进行序列化,对象的代码也需要高度优化。
因此,很明显实现Parcelable并不容易。实现Parcelable接口需要写大量的模板代码,这使得对象代码变得难以阅读和维护。
1、新建User.java:
public class User implements Parcelable{
private String name;
private int age;
public String getName() {
return name;
}
public int getAge() {
return age;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public User(String name,int age){
this.name = name;
this.age = age;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(getName());
dest.writeInt(getAge());
}
public static final Creator<User> CREATOR = new Creator<User>() {
@Override
public User createFromParcel(Parcel source) {
return new User(source.readString(),source.readInt());
}
@Override
public User[] newArray(int size) {
return new User[size];
}
};
}
2、MainActivity.java:
i.putExtra("user",new User("Android",2));
、TheAty.java:
User user = (User) i.getParcelableExtra("user");
tv.setText(String.format("User info(name=%s,age=%d)",user.getName(),user.getAge()));
最新文章
- java 连接接数据库 中的代码 放到配置文件中
- 仿QQ的底部选项
- Spring AOP在函数接口调用性能分析及其日志处理方面的应用
- Redis-cluster集群【第四篇】:redis-cluster集群配置
- 【转】svn服务器IP修改后,本地怎么跟新svn同步,svn relocate 操作
- leetcode_最长公共前缀
- [Drools]JAVA规则引擎 -- Drools
- PHP生成缩略图函数
- vue视频学习笔记02
- MySQL PHP 语法
- wing带你玩转自定义view系列(3)模仿微信下拉眼睛
- C# 添加Windows服务,定时任务。
- redis的一些修改
- 腾讯云CVM之间配置免密钥登录
- centos7.5 安装mysql8.0.13
- 比较字典推导式/dict()/通过键来构造的字典的速率 笔记
- Linux:使用读写锁使线程同步
- Amaze UI 云适配
- anu - proptypes
- Mysql的两种引擎的区别