Search code examples
javajsonclassdesign-patternspojo

How to avoid duplicated classes in classes with defined fields and no methods


I have a lot of similar classes to create with defined fields, no need constructors, methods.

Sample classes:

public class Adam {
   private String name = "Adam";
   private int code = 1;
}

public class Brian {
   private String name = "Brian";
   private int code = 2;
}

and about 100 or more similar classes, 12 fields in class. All defined.

I would like to have access like eq: Class.fieldname or similar handy way.

Later I want to make a json object using this class like

{ name: "Adam", code: "1" }

and use it in rest assured framework: https://rest-assured.io/

Maybe storing this kind of data as classes in not good solution? any idea?

PS: no possibility to keep them in dB.


Solution

  • That seems very inefficient in code reuse. You should have a Person class or something similar. Each person should be an instance. Since Java 14 you can simplify this usage with the use of the record keyword.

    Example:

    public record Person (String name, int code) {}
    

    Getter/setters are autogenerated.

    p = new Person("Adam", 1);
    p.name() // returns name
    

    If code is an unique id then you can use a Map or Vector to keep track of the instances.