例如,简单的Parcelable
实现:
public class Student implements Parcelable {
public static final Creator<Student> CREATOR = new Creator<Student>() {
@Override
public Student createFromParcel(Parcel parcel) {
return new Student(parcel);
}
@Override
public Student[] newArray(int size) {
return new Student[size];
}
};
private final Integer academicYear;
private final Integer age;
private final String name;
public Student() {
this.name = null;
this.age = null;
this.academicYear = null;
}
public Student(String name, int age, int academicYear) {
this.name = name;
this.age = age;
this.academicYear = academicYear;
}
public Student(Student origin) {
this.name = origin.getName();
this.age = origin.getAge();
this.academicYear = origin.getAcademicYear();
}
public Student(Parcel in) {
this.name = in.readString();
this.age = (Integer) in.readValue(Integer.class.getClassLoader());
this.academicYear = (Integer) in.readValue(Integer.class.getClassLoader());
}
@Override
public void writeToParcel(Parcel out, int i) {
out.writeString(name);
out.writeValue(age);
out.writeValue(academicYear);
}
@Override
public int describeContents() {
return 0;
}
public String getName() {
return name;
}
public Integer getAge() {
return age;
}
public Integer getAcademicYear() {
return academicYear;
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof Student)) {
return false;
}
Student other = (Student) obj;
return (Objects.equal(getName(), other.getName()) &&
Objects.equal(getAge(), other.getAge()) &&
Objects.equal(getAcademicYear(), other.getAcademicYear()));
}
@Override
public int hashCode() {
return Objects.hashCode(getName(), getAge(), getAcademicYear());
}
@Override
public String toString() {
return Objects.toStringHelper(this)
.add("name", getName())
.add("age", getAge())
.add("academicYear", getAcademicYear())
.toString();
}
}
此测试未通过:
public void testParcelable() {
Student studentIn = new Student("Jack", 19, 2);
Parcel parcel = Parcel.obtain();
studentIn.writeToParcel(parcel, 0);
Student studentOut = Student.CREATOR.createFromParcel(parcel);
assertEquals(studentIn, studentOut);
}
预期:学生{name = Jack,年龄= 25,academicYear = 6}但是 是:学生{name = null,age = null,academicYear = null}
有什么问题?如何正确地使用Parcel
来测试Parcelable
实施?
或者我应该使用Intent
而不是Parcel
?如果我使用Intent
,那么测试通过。