• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • Ron McLeod
  • Jeanne Boyarsky
  • Paul Clapham
Sheriffs:
  • Liutauras Vilda
  • Henry Wong
  • Devaka Cooray
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Al Hobbs
  • Carey Brown
Bartenders:
  • Piet Souris
  • Mikalai Zaikin
  • Himai Minh

using reflection to get getter of field?

 
Ranch Hand
Posts: 141
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
So I have a POJO named foo with fields and associated getters and setters.

I'd like to iterate through all the fields of the class and grab each fields' type ( String, Long, etc) and value.



alternately, given you know a Field, how can you know it's corresponding getter/setter?


TIA,


Still-learning Steve
 
Sheriff
Posts: 22662
127
Eclipse IDE Spring VI Editor Chrome Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The setter should be called after the field -- the field name with a capital first letter, preceded by set. So if you find a field myValue of some type T, the setter should be setMyValue(T).

For the getter there are two options:
1) the return type is boolean. The getter should be isMyValue() or hasMyValue() (both are allowed)
2) the return type is not boolean. The getter should be getMyValue()
 
Stuart Rogers
Ranch Hand
Posts: 141
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks for the reply! I'll do some experimenting. I'm trying to concoct a clever scheme for writing out selected fields based on enums embedded in the class.


Still-learning steve
 
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Note, you do not have to do the magic of creating the method names yourself, using the rules that Rob listed. Java has a special API for this, the JavaBeans API, in package java.beans.

Example:

(Note: Untested code, I'm sure I forgot catching or throwing some exceptions, but you get the idea...!)
reply
    Bookmark Topic Watch Topic
  • New Topic