Get your CodeRanch badge!*
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


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Extracting Method names based on Fields" Watch "Extracting Method names based on Fields" New topic
Author

Extracting Method names based on Fields

amit punekar
Ranch Hand

Joined: May 14, 2004
Posts: 507
Hi,
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,
Amit


Regards,
Amit
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24166
    
  30

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


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

Joined: May 14, 2004
Posts: 507
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.

Thoughts
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
Amit
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Extracting Method names based on Fields
 
Similar Threads
getXXX(int i) method
getter not returning subclass instance variable values set by setter
XDoclet: generating a many-to-one mapping in hibernate with access="field"
Mapping annotations for variables.
Polymorphism and "this" keyword, an interesting Q..