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?
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With