-1

I have the below class with around 200 variables.

public class BaseDataDTO {

    private CSVRecord rawData;

    private List<InquiriesDataDTO> inquiriesData;
    private ListTradesDataDTO> tradesData;
    private List<CollectionsDataDTO> collectionsData;

    private Long applicantId;

    //cvv attributes
    public String adg001;
    private String adg002;
    private String adg003;
    private String adg004;
    private String apg05;
    -
    -
    private String apg199;
}

From a different class, I would like to access the instance variables through the variable names, is it possible to do? I need to do this since I need compare some another response with the instance variable of that class through a Map key. How can I achieve some thing to the effect of the text in bold below?

I do not want to use getter methods here since it is in a for loop for 200 times.

BaseDataDTO baseData = CSVParser.parseBaseData(fileName);

Map<String, String> attributes = fileLoader.withName("attributes.json").jsonToObject(Map.class);
        
for (String key : attributes.keySet()) {
String responseValue = response.getModelScores().get(0).getScoringInput().get("function_input").get(key).asText();
String expValue = baseData.get(key));
AssertEquals(responseValue, expValue);
}

user3818494
  • 29
  • 1
  • 1
  • 7
  • 4
    *"I have the below class with around 200 variables"* -- isn't this a problem that first needs to be fixed? Then we can address what looks to be an [XY Problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) type question. – Hovercraft Full Of Eels Feb 05 '22 at 06:55
  • 1
    They’d have to not be `private` at the very least… – Boris the Spider Feb 05 '22 at 06:56
  • Use the public access modifier, the private prevents you from doing that, that's why you use getters and setters so you wouldn't directly use the object's attributes directly. It is safer and provides more security. – Enis Feb 05 '22 at 07:09
  • 2
    Does this answer your question: https://stackoverflow.com/questions/23931546/java-getter-and-setter-faster-than-direct-access 200 iterations are nothing. Anyway it's a bad practice to make everything `public` – Gayan Weerakutti Feb 05 '22 at 07:25

1 Answers1

-2

Create a BaseDataDTO from your Map and check for equality via equals.

Never ever access object fields by their name string, unless you are writing low level libraries like parsers.

Accessing fields by name is done via Reflection:

String expValue = (String) BaseDataDTO.class.getDeclaredField(key).get(baseData)

Note that stuff like this is at least an order of magnitude slower than using a getter.

w_n
  • 345
  • 3
  • 7