mercredi 23 septembre 2015

java reflection invoke setter with Object type parameter

I am quite new in java. Please help me to find the way to invoke method with an Object parameter.

Here's my sample code:

public class Myclass {

private Foo foo;
private Bar bar;

public void setFoo(Foo foo) {
   this.foo = foo
}

public void setBar(Bar bar) {
   this.bar = bar
}

I tried to used jackson library to convert from HashMap to MyClass. But It didn't work for me.

ObjectMapper mapper = new ObjectMapper();
mapper.convertValue(myHashMap, MyClass);`            // jackson library

But it still couldn't parse Date, Long And other Specific classes.

Then I change the way to do it by myself using reflection.

final Map<String, Method[]> methods = new HashMap<String, Method[]>();
for (PropertyDescriptor pd : Introspector.getBeanInfo(bean.getClass(), Object.class).getPropertyDescriptors()) {
    methods.put(pd.getName(), new Method[]{ pd.getReadMethod(), pd.getWriteMethod()});
}

...

public void putAll(HashMap<String, Object> map, Object object) {
    Iterator it = map.keyset().iterator();
    while(it.hasNext()) {
        String key = (String) it.next();
        Method[] m = methods.get(key);
        m[1].invoke(object, map.get(key));          // Error here.
    }
}

With this code. I have exception with argument mismatch. How do I solve this ? Or the only way I have to do is get the parameter type to check and cast every object to match the setter ?

Thank in advance.





Aucun commentaire:

Enregistrer un commentaire