Bilesh Ganguly
Bilesh Ganguly

Reputation: 4131

How to create and then instantiate POJO classes dynamically?

Certain specifications of my project require me to create POJO classes from information provided via an excel sheet or JSON; then creating objects of that class with relevant information at hand that will be used later in the code.

Extracting relevant data from excel sheets and JSON is not an issue. I was even able to create POJO classes dynamically thanks to this answer. But I'm unsure if it is possible to create objects of this class. As this guy mentioned in his above answer that -

But the problem is: you have no way of coding against these methods, as they don't exist at compile-time, so I don't know what good this will do you.

Is it possible to instantiate the class created in the above answer? If so, how? If not, what are other alternatives to this problem? Or should I change my approach regarding this specification and think of some other option?

Upvotes: 2

Views: 7615

Answers (2)

Kartic
Kartic

Reputation: 2985

Probably in your situation I would go for something like below. This could not be post as a comment. So posting here.

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class GenericDTO {

    private Map<String, List<Object>> resultSetMap = new HashMap<String, List<Object>>() ;

    public void addAttribute(String attributeName, Object attributeValue) {
        if(resultSetMap.containsKey(attributeName)) {
            resultSetMap.get(attributeName).add(attributeValue);
        } else {
            List<Object> list = new ArrayList<Object>();
            list.add(attributeValue);
            resultSetMap.put(attributeName, list);
        }
    }

    public Object getAttributeValue(String key) {
        return (resultSetMap.get(key) == null) ? null : resultSetMap.get(key).get(0); 
    }

    public List<Object> getAttributeValues(String key) {
        return resultSetMap.get(key); 
    }

}

You can use it like:

GenericDTO dto = new GenericDTO();
dto.addAttribute("aa", 1);
dto.addAttribute("aa", "aa");
dto.addAttribute("bb", 5);

System.out.println(dto.getAttributeValue("bb"));
System.out.println(dto.getAttributeValues("aa"));

Upvotes: 1

leftbit
leftbit

Reputation: 838

You can use reflection to instantiate the generated classses and access the provided methods.

Upvotes: 1

Related Questions