重用另一个类中的字段

我有两个类似于这些的POJO:

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class User {

    @SerializedName("name")
    @Expose
    private String name;

    @SerializedName("mail")
    @Expose
    private String mail;

    ....
}
public class Profile {

    @SerializedName("birthday")
    @Expose
    private String birthday;

    @SerializedName("biography")
    @Expose
    private String biography;

    .....
}

现在我需要第三个POJO重用他们的某些字段:

public class RegisterInfo {

    @SerializedName("name")
    @Expose
    private String name;

    @SerializedName("birthday")
    @Expose
    private String birthday;
}

我不想在RegisterInfo类中重复代码。 因此,在修改“名称”或“生日”字段的情况下,我只需要触摸一个类中的代码即可。 那么...有什么方法可以对我的RegisterInfo类中的“名称”和“生日”字段进行“引用”?

evilor110 回答:重用另一个类中的字段

您可以对字段使用相同的常量,但是重复声明。这样,如果json键更改,则可以轻松一次更改所有键。您可以对常量进行静态导入,以使代码看起来像下面这样整洁。

Class JsonConstants {

  final static String JSON_NAME = "name" 
  final static String JSON_MAIL = "mail"
  final static String JSON_BIRTHDAY = "birthday"
  final static String JSON_BIOGRAPHY = "biography"

}    

public class User {

  @SerializedName(JSON_NAME)
  @Expose
  private String name;

  @SerializedName(JSON_MAIL)
  @Expose
  private String mail;

     ....
}

public class Profile {

  @SerializedName(JSON_BIRTHDAY)
  @Expose
  private String birthday;

  @SerializedName(JSON_BIOGRAPHY)
  @Expose
  private String biography;

  .....
}

public class RegisterInfo {

  @SerializedName(JSON_NAME)
  @Expose
  private String name;

  @SerializedName(JSON_BIRTHDAY)
  @Expose
  private String birthday;
}
本文链接:https://www.f2er.com/2895256.html

大家都在问