Solved

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

Posted on 2006-10-23
3
279 Views
Last Modified: 2012-06-21
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
Comment
Question by:mscprojhk
  • 2
3 Comments
 
LVL 92

Expert Comment

by:objects
Comment Utility
Method m = o.getClass().getMethod("set"+paramName, new Object[] { String.class });

you will need to capitalize the param name if not already provided
0
 
LVL 92

Expert Comment

by:objects
Comment Utility
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
 
LVL 9

Accepted Solution

by:
shinobun earned 50 total points
Comment Utility
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

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now