This week's book giveaway is in the OCAJP forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide 1Z0-808 and have Jeanne Boyarsky & Scott Selikoff on-line! See this thread for details.
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
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.