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

  • How about Spring's BeanWrapper? Get an instance via [PropertyAccessorFactory](http://docs.spring.io/spring-framework/docs/2.5.2/api/org/springframework/beans/PropertyAccessorFactory.html) – dnault May 09 '16 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? – Jose Martinez May 09 '16 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. – ManoDestra May 09 '16 at 20:57

2 Answers2

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);
}
fhofmann
  • 847
  • 7
  • 15
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");
            }
        }
    }
}
user2959589
  • 362
  • 1
  • 9
  • 23