0

For the input like below, I would like to invoke it's respective setter method. For example Input:

name | age
abc | 32
bac | 43

The above input will be stored under "List<Map<String, String>>" and I should be able to find setName for "name" and setAge for "age" and assign "abc" to setName and 32 to setAge. Both setName and setAge is declared in a Java file.

I have explored BeanUtils and Reflection API yet trying to find a solution.

Kindly share your opinion to achieve my requirement

3
  • How about Spring's BeanWrapper? Get an instance via PropertyAccessorFactory Commented May 9, 2016 at 17:19
  • can we assume that the key will be lowercase and the first letter after "set" in the setter will be upper case? Commented May 9, 2016 at 17:30
  • You say you've "explored" the Reflection API, yet you haven't posted what you've tried so far that isn't working. Post what you've tried to assist others in helping you. Commented May 9, 2016 at 20:57

2 Answers 2

0

If your List is populated like:

Map<String, String> m = new HashMap<>();
m.put("age","32");
m.put("name","abc");
list.add(m);

With reflection your code should be something like:

List<YourObject> resultList = new ArrayList<>(); // or List<Object> 
for(Map<String, String> map: list){
   YourObject obj = new YourObject();// or Object obj = Class.forName("package.YourObject").newInstance();
   for(String key: map.keySet()) {
     String method = "set" + key.substring(0,1).toUpperCase() + key.substring(1);
     obj.getClass().getDeclaredMethod(method, String.class).invoke(obj, map.get(key));
   }
   resultList.add(obj);
}
Sign up to request clarification or add additional context in comments.

Comments

0

Super easy to do with Reflection, if that is what you are looking for:

An object with a setter:

public class ObjWithSetters {
    private static final PrintStream out = System.out;

    public void setName(String name) {
        out.println("Setting the name: " + name);
    }    
}

And here is how to search it:

public class FindSetter {

    private static final Logger LOG = Logger.getLogger(FindSetter.class.getName());

    public static void main(String[] args) throws Exception {
        final Object myObject = new ObjWithSetters();

        final Method[] methods = myObject.getClass().getMethods();
        for(Method m : methods) {
            if(m.getName().equals("setName")) {
                m.invoke(myObject, "My name is Bob");
            } else {
                LOG.info("I found this method: " + m.getName() + " but it is not the setter I want");
            }
        }
    }
}

1 Comment

Thanks for your time and inputs. The inputs has shed some light on how I should proceed.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.