-1

I have java object

public class ClientDuplicationVerificationData {

    public final String firstname;
    public final String middlename;
    public final String lastname;
    public final String fullname;
    public final String displayName;
    public final String mobileNo;
    public final LocalDate dateOfBirth;
    public final CodeValue gender;
}

I just need to access one of the variable as generic for example

String variable = "middlename";
ClientDuplicationVerificationData clientDuplicationVerificationData  =  new ClientDuplicationVerificationData ();

clientDuplicationVerificationData.variable;

According to some conditions the variable may be changing.

sometimes it may be lastName,gennder,dateOfBirth and so on

is there any way to do this?

BackSlash
  • 21,927
  • 22
  • 96
  • 136

1 Answers1

0

You can use Class.getDeclaredFields() to get all declared fields of the class. You can use Field.get(currentObject) to get the value of the currentObject.

In your example it would be like this

clientDuplicationVerificationData.getClass().getDeclaredField(variable).get(clientDuplicationVerificationData);
Sergei Podlipaev
  • 1,331
  • 1
  • 14
  • 34