Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invoking setter method using java reflection

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?

like image 945
Dilini Rajapaksha Avatar asked Apr 04 '12 10:04

Dilini Rajapaksha


People also ask

What tag is used to invoke the setter method of beans?

Using * to call all setter methods of java bean The property attribute of <jsp:setProperty> contains '*' as its value. This tag calls only those setter methods of the property whose names are available in the requested form field.

What is reflection method in Java?

Reflection is a feature in the Java programming language. It allows an executing Java program to examine or "introspect" upon itself, and manipulate internal properties of the program. For example, it's possible for a Java class to obtain the names of all its members and display them.


1 Answers

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 
like image 52
Anand Avatar answered Sep 28 '22 10:09

Anand