首页 > 解决方案 > 在另一个类中重用字段

问题描述

我有两个类似于这些的 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 类中对“姓名”和“生日”字段进行“引用”?

标签: javaclassgsonpojo

解决方案


您可以对字段使用相同的常量,但重复声明。这样,如果 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;
}

推荐阅读