有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何使用生成器模式实现类的Parcelable

如何用一个包含Builder模式的类实现Parcelable

public class Leave implements Parcelable {

    private final String id;
    private final String type;
    private final String status;
    private final String approver;

    public static class Builder {
        private String id;
        private String type;
        private String status;
        private String approver;

        public Builder id(String id) { this.id = id; return this; }
        public Builder type(String type) { this.type = type; return this; }
        public Builder status(String status) { this.status = status; return this; }
        public Builder approver(String approver) { this.approver = approver; return this; }

        public Leave build() {
            return new Leave(this);
        }
    }

    private Leave(Builder builder) {
        this.id = builder.id;
        this.type = builder.type;
        this.status = builder.status;
        this.approver = builder.approver;
    }

    public String getId() {
        return id;
    }

    public String getType() {
        return type;
    }

    public String getStatus() {
        return status;
    }

    public String getApprover() {
        return approver;
    }

    public static final Parcelable.Creator<Leave> CREATOR = new Parcelable.Creator<Leave>() {
        public Leave createFromParcel(Parcel in) {
            return new Leave(in);  // ERROR! Leave(Parcel) is undefined
        }                          // Builder has a private constructor leaving
                                   //     a single instance;

        public Leave[] newArray(int size) {
            return new Leave[size];
        }
    };

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(id);
        dest.writeString(type);
        dest.writeString(status);
        dest.writeString(approver);      
    }
}

共 (1) 个答案

  1. # 1 楼答案

    需要添加地块零件,请执行以下操作:

    public Leave(Parcel in)
    {              
      this.id = in.readString();
      this.type = in.readString();
      this.status = in.readString();
      this.approver = in.readString();
    }