Alex Rivera | Logout

Invoking setter method using java reflection

Asked 2012-04-04T10:08:57.263
58

I need to invoke the setter methods of a class using reflection, and the code is as below:

try {             
   Method method = myObj.getClass().getMethod("set" + fieldName, new Class[] { value.getClass() });               
   method.invoke(myObj, value);
     } catch (Exception ex) {
         ex.printStackTrace();
     }

The value is an ArrayList and the setter method is as below:

public void setNames(List<String> names){
    this.names = names;
}

A java.lang.NoSuchMethodException is thrown when running this code, but when the setter method parameter type is changed to ArrayList from List it executes fine. Is there a way to keep the setter method parameter in super type and still use reflection without manually giving the type of the parameter when getting the method from the class?

Edit
Report

2 Answers

61

You could use BeanUtils:

Step #1

Customer customer = new Customer();

Step #2

BeanUtils.setProperty(customer,"firstName","Paul Young");

You could iterate all class members using reflection and set values accordingly, assuming customer object has:

private String firstName;
// Getter and Setter are defined
answered 2012-07-05T07:48:46.813
5

There is a simple solution, but that simplicity comes at the cost of performance.

I'm using this monster instead:

public static Method findMethod(Class<?> clazz, String methodName, Class<?>... parameterTypes) throws NoSuchMethodException {

    // First try the trivial approach. This works usually, but not always.
    try {
        return clazz.getMethod(methodName, parameterTypes);
    } catch (NoSuchMethodException ex) {
    }

    // Then loop through all available methods, checking them one by one.
    for (Method method : clazz.getMethods()) {

        String name = method.getName();
        if (!methodName.equals(name)) { // The method must have right name.
            continue;
        }

        Class<?>[] acceptedParameterTypes = method.getParameterTypes();
        if (acceptedParameterTypes.length != parameterTypes.length) { // Must have right number of parameters.
            continue;
        }

        boolean match = true;
        for (int i = 0; i < acceptedParameterTypes.length; i++) { // All parameters must be right type.
            if (null != parameterTypes[i] && !acceptedParameterTypes[i].isAssignableFrom(parameterTypes[i])) {
                match = false;
                break;
            }
            if (null == parameterTypes[i] && acceptedParameterTypes[i].isPrimitive()) { // Accept null except for primitive fields.
                match = false;
                break;
            }
        }

        if (match) {
            return method;
        }

    }

    // None of our trials was successful!
    throw new NoSuchMethodException();
}

parameterTypes are what you get from your value.getClass(). Some or all of them can be also null. Then they are treated as matces for any non-primitive parameter fields.

Even this isn't quit perfect: If there are several methods that

answered 2012-04-04T10:18:26.863

Your Answer