You can do something like this. You can make this code more generic so that you can use it for looping on fields:

Class aClass = f.getClass();
Class[] paramTypes = new Class[1];
paramTypes[0] = String.class; // get the actual param type

String methodName = "set" + fieldName; // fieldName String
Method m = null;
try {
    m = aClass.getMethod(methodName, paramTypes);
} catch (NoSuchMethodException nsme) {
    nsme.printStackTrace();
}

try {
    String result = (String) m.invoke(f, fieldValue); // field value
    System.out.println(result);
} catch (IllegalAccessException iae) {
    iae.printStackTrace();
} catch (InvocationTargetException ite) {
    ite.printStackTrace();
}
Answer from Ankit Bansal on Stack Overflow
Top answer
1 of 2
3

Have you tried getting all the methods of the invoked class and filtering out only the getter methods by name and invoking them?

 Method[] methods =  cls.getClass().getDeclaredMethods();

             for (Method m: methods) {
                 if(m.getName().startsWith("get")) {
                     m.invoke(clsInstance);
                 }
             }

This solves our half problem, as getters are invoked without any arguments. But if you need to invoke a setter method you need to specify arguments. Ex, To invoke a setter which accepts string argument method as below:

m.invoke(clsInstance, "some string argument");

One solution to could be make all the setters accept an object type value and typecast them while assigning it to actual class variables.

Now your pojo classes will look as below:

public class AccountPojo {

private String dataList;
private String dataSet;

public String getDataList() {
    return dataList;
}

public void setDataList(Object dataList) {
    this.dataList = (String) dataList;
}

public String getDataSet() {
    return dataSet;
}

public void setDataSet(Object dataSet) {
    this.dataSet = (String)dataSet;
}
} 

public class GetAccountsPojo {

private String accountId;
private int noOfAccounts;

public String getAccountId() {
    return accountId;
}

public void setAccountId(Object accountId) {
    this.accountId = (String) accountId;
}

public int getNoOfAccounts() {
    return noOfAccounts;
}

public void setNoOfAccounts(Object noOfAccounts) {
    this.noOfAccounts = (int) noOfAccounts;
}
}

Add below code to your main method:

for (Method m: methods) {
  if(m.getName().startsWith("get")) {
    m.invoke(clsInstance);
  }
  if(m.getName().startsWith("set")) {
    m.invoke(clsInstance, "any argument to be passed here");
  }

}
2 of 2
1

Don't use raw class. If you know which class is called already, use typed class.

    try {
        AccountPojo obj = AccountPojo.class.newInstance();
        Method setDataList = AccountPojo.class.getMethod("setDataList");
        setDataList.setAccessible(true); // This is important if you want to access protected or private method. For public method you can skip
        setDataList.invoke(obj, "123");
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (InstantiationException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    }
Discussions

java - Dynamic getter method creation - Stack Overflow
I have created dynamic setter getter using Reflection API but it is creating performance issue so I want to replace my reflection code with some dynamic cutom method specially for getter. I am pla... More on stackoverflow.com
🌐 stackoverflow.com
java - Adding getters and setters dynamically to existing class - Stack Overflow
Any once suggest me how can I add getters and setters dynamically to existing class? I need to create the instance of same class for further use. I will be having Pojo class at compile time. At run time reading property file and need to create getters and setters those entities ... Reflection can be used to set/get values. (Beware of performance impacts.) Add some details to your question. ... it's a little difficult to understand - are you looking for a tool to generate java ... More on stackoverflow.com
🌐 stackoverflow.com
November 7, 2012
java - Spring boot - How to Write Setter and Getter field Name Dynamic way - Stack Overflow
I am getting the record last 6 months from the database. Based on the current Date. I am storing into an JSONArray when I am returning it - I am getting Serialization Error, because there is not Ge... More on stackoverflow.com
🌐 stackoverflow.com
java - Dynamic data object generation - Code Review Stack Exchange
Last weekend I had an idea: Why not remove dozens of classes by removing all the basic get/set/equals/hashCode implementation of my data object interfaces? I tend to code against interfaces, so I More on codereview.stackexchange.com
🌐 codereview.stackexchange.com
August 10, 2015
🌐
Medium
medium.com › @narasimha4789 › inside-your-ide-the-magic-of-instant-getter-and-setter-generation-6686abda8669
Inside Your IDE: The Magic of Instant Getter and Setter Generation | by Raju Methuku | Medium
November 9, 2024 - The getter (getName()) retrieves the name, while the setter (setName(String name)) updates it. Simple, right? Now let’s add some magic to it! Using Java’s Reflection API, we can dynamically load a class, access its fields, and even generate ...
🌐
Javalite
javalite.io › setters_and_getters
JavaLite - setters and getters
With ActiveJDBC you can use dynamic getters and setters or write wrapper getter and setter methods. Please, see Recommendation below for more information. ... Person p = Person.findById(); String name = p.getString("name"); Timestamp dob = p.getTimestamp("dob"); ... ActiveJDBC will do all possible ...
🌐
Coderanch
coderanch.com › t › 455851 › java › generate-Dynamic-Setter-Method
How to generate Dynamic Setter Method Name (Java in General forum at Coderanch)
July 27, 2009 - Dynamically generate Setter Name in my Application. Now run setName() when I get name and setAge() when I get age .
🌐
YouTube
youtube.com › watch
Generating Getters And Setters methods Java Reflection
Enjoy the videos and music you love, upload original content, and share it all with friends, family, and the world on YouTube.
🌐
Oracle
docs.oracle.com › cd › E19698-01 › 816-7609 › 6mdjrf83h › index.html
2.2 Implementing a Dynamic MBean
And since most dynamic MBeans will always be instantiated with the same management interface, building the MBeanInfo object is fairly straightforward. Example 2–2 shows how the SimpleDynamic MBean defines its management interface, as built at instantiation and returned by its getMBeanInfo method. Generic getters and setters take a parameter that indicates the name of the attribute to read or write.
🌐
Project Lombok
projectlombok.org › features › GetterSetter
@Getter and @Setter
You can annotate any field with @Getter and/or @Setter, to let lombok generate the default getter/setter automatically. A default getter simply returns the field, and is named getFoo if the field is called foo (or isFoo if the field's type is boolean). A default setter is named setFoo if the ...
Find elsewhere
🌐
Oracle
docs.oracle.com › cd › E19206-01 › 816-4178 › dynamic-10 › index.html
Generic Attribute Getters and Setters
In a dynamic MBean, you must modify the generic methods that encode all attributes.
🌐
OpenCredo
opencredo.com › blogs › new-tricks-with-dynamic-proxies-in-java-8-part-3
New Tricks With Dynamic Proxies In Java 8 (part 3)
public class BeanProxy implements MethodInterpreter { public static T proxying(Class iface) { return Proxies.simpleProxy(iface, new BeanProxy()); } private Map<String, Object> store = new HashMap(); @Override public MethodCallHandler interpret(Method method) { if (isGetter(method)) { return (proxy, args) -> store.get(getPropertyName(method)); } if (isSetter(method)) { return (proxy, args) -> store.put(getPropertyName(method), args[0]); } throw new IllegalArgumentException("Method " + method + " is neither a getter nor a setter."); } // Implementations of isGetter, isSetter and getPropertyName go here }
Top answer
1 of 1
2

There are few things which I am assuming, because as per your details the question is somewhat unclear.

You have a database having records as per what you have mentioned in your question.

[
   {
       "userName": "Sita",
       "userEmail": "[email protected]",
       "January": 3,
       "February": 10,
       "March": 1,
       "April": 3,
       "May": 32,
       "June": 31
   }
]

Its basically Json Object contained inside Json Array, So, as per Java you will have a Entity class to hold the values and that Entity class will be contained inside a List.

@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
class Details{
    private String userName;
    private String January;
    private String February;
    private String March;
    private String April;
    private String May;
    private String June;
    private String July;
    private String August;
    private String September;
    private String October;
    private String November;
    private String December;
}

Your result after fetching the data from database will be something like,

List<Details> result = //database call (Repository call);

Now, this all things will be happening inside some service class , we are calling that service class as DetailsServiceImpl.java

Repository

@Repository
interface DetailsRepository extends JpaRepository<Details,Long>{
    
}

Service

@Service
@RequiredArgsConstructor
class DetailsServiceImpl{
    private final DetailsRepository detailsRepository;
    
    public List<DetailsDto> getLastSixMonthsData(){
        //List<Details> result = //detailsRepository database call;

        //either use Modelmapper to copy the data from entity to DTO
        //BeanUtils can also be used.
        return //Copied ArrayList<DetailsDto>(); which will be populated by ModelMapper or BeanUtils.
    }
}

DTO This DTO is responsible for rendering the data to controller, or you can say sending the representable data to controller.

@Data
//@JsonInclude(JsonInclude.Include.NON_NULL) can be used if you dont want non-null values in your response.
class DetailsDto{
    private String userName;
    private String January;
    private String February;
    private String March;
    private String April;
    private String May;
    private String June;
    private String July;
    private String August;
    private String September;
    private String October;
    private String November;
    private String December;
}

RestController

@RestController
@RequiredArgsConstructor
class DetailsController{
    private final DetailsServiceImpl detailsService;
    public ResponseEntity<List<DetailsDto>> getDetailsLastSixMonths(){
        return new ResponseEntity<List<DetailsDto>>(detailsService.getLastSixMonthsData(), HttpStatus.OK);
    }
}

Links to follow How to use BeanUtils.copyProperties?

Copy one class properties to another class, with set the field to map in java Spring boot

No need to use JSONObject and operating on each object. Hope it helps.

🌐
Medium
medium.com › @revalinaprinawan05 › creating-getters-and-setters-in-java-example-program-77728188d5b7
Creating Getters and Setters in Java: Example Program | by Revalina Azahra Prinawan | Medium
March 20, 2024 - This allows us to refactor or optimize classes without breaking other parts of the code that depend on them. The first step is to create a project, package, and class beforehand. For instructions on how to create them, you can click the following ...
🌐
CodeJava
codejava.net › coding › java-getter-and-setter-tutorial-from-basics-to-best-practices
Java Getter and Setter Tutorial - from Basics to Best Practices
September 30, 2019 - With primitive types (int, float, double, boolean, char…), you can freely assign/return values directly in setter/getter because Java copies value of one primitive to another instead of copying object reference.
🌐
Reddit
reddit.com › r/learnjavascript › dynamic getter/setter
r/learnjavascript on Reddit: Dynamic getter/setter
August 28, 2022 -

Let's say we have a typescript class:

class Test {
    private _value = 0;

    public set value(val: number) {
        this._value = val;
    }

    public get value() {
        return this._value;
    }
}

Is there a way to create one dynamic getter/setter value1, value2, value3, .... valueN without defining each of them separately?

🌐
GeeksforGeeks
geeksforgeeks.org › java › getter-and-setter-in-java
Getter and Setter in Java - GeeksforGeeks
June 22, 2023 - For the program's convenience, the getter starts with the word "get" followed by the variable name. Setter in Java: While Setter sets or updates the value (mutators). It sets the value for any variable used in a class's programs.