File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes Extracting Method names based on Fields Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Extracting Method names based on Fields" Watch "Extracting Method names based on Fields" New topic

Extracting Method names based on Fields

amit punekar
Ranch Hand

Joined: May 14, 2004
Posts: 544
I have a scenario where I need to invoke the getXXX() method based on the field name I retrieve from a list.
I tried using reflection to access the fields but because the fields are private I am not able to access them.
I was looking at an option to generate the getXXX() method name and then use class.getMethod() and invoke it.
I may not use this way because in case of a field name having multiple words I may not know which letters to be upper cased.
for e.g for the field named such as emailId the getter would be getEmailId().
Thanks in advance,

Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24199

Have a look at the java.beans.Introspector class.

[Jess in Action][AskingGoodQuestions]
amit punekar
Ranch Hand

Joined: May 14, 2004
Posts: 544
Hi sheriff,
Apologies for delayed reply. Thanks for your inputs. I have implemented the thing which I asked about using java.beans and java.lang.reflect.
I am keeping the field names in a properties file mapped to some keys and then reading the field names to retrieve the getter methods.

The main issue I had was to get rid of several if/else statements to populate the JSON object based upon the fields in the java bean. For e.g I am reading set of field names which needs to go in JSON object from a property file and then based on that had logic with if.else to call individual method. I didnt like that way of programming so looking for this solution.

1) Another thing which is coming to my mind is that if getter has various return types(of course it will have in practical scenario) then will I end up writing the if..else to check the datatype and populate the values in another bean or whatever.

Anyways I did not face the issue mentioned above(Thoughts 1) because I am straight away putting whatever value returned (m.invoke() returns Object) in the JSON object which has all the strings.
Just wanted to surface what came in my mind hence wrote the above issue.

Thanks once again
subject: Extracting Method names based on Fields
It's not a secret anymore!