[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 301
  • Last Modified:

How to use Reflection API or other method to call setter method

For, I have an class with several setter/getter methods
e.g.

Class1

setAddress(String address)
String getAddress()

setEmailAdddress(String email)
String getEmail

And I want to choose the setter method at a java application based on the param value

How to do so?

0
mscprojhk
Asked:
mscprojhk
  • 2
1 Solution
 
objectsCommented:
Method m = o.getClass().getMethod("set"+paramName, new Object[] { String.class });

you will need to capitalize the param name if not already provided
0
 
objectsCommented:
sorry, typo should be:

Method m = o.getClass().getMethod("set"+paramName, new Class[] { String.class });

and to call it:

m.invoke(o, new Object[] { value});
0
 
shinobunCommented:
You can use Apache Jakarta Commons' Beanutils [1] for that kind of operation.  PropertyUtils [2] has most everything a bean manipulator wants.  :)

Class1 yourObject = new Class1();
String newAddress = "221B Baker St.";
PropertyUtils.setProperty(yourObject, "address", newAddress);

[1] http://jakarta.apache.org/commons/beanutils/
[2] http://jakarta.apache.org/commons/beanutils/commons-beanutils-1.7.0/docs/api/org/apache/commons/beanutils/PropertyUtils.html
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now