Alfonso_MA
Alfonso_MA

Reputation: 555

Reusing fields in another class

I have two POJOs similar to these:

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;

    .....
}

Now I need a third POJO reusing some of their fields:

public class RegisterInfo {

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

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

I don't want to duplicate code in my RegisterInfo class. So in case of modification of the fields 'name' or 'birthday' I would just have to touch the code in one single class. So...is there any way to make a 'reference' to the 'name' and 'birthday' fields from my RegisterInfo class?

Upvotes: 0

Views: 423

Answers (1)

Cory Roy
Cory Roy

Reputation: 5619

You could use the same constant for the fields, but repeat the declaration. That way, if the json keys change, you can easily change all the keys at once. You can do static imports for the constants to make the code look tidy like below.

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;
}

Upvotes: 1

Related Questions