Win a copy of Modern JavaScript for the Impatient this week in the Server-Side JavaScript and NodeJS forum!
  • 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Bear Bibeault
  • Junilu Lacar
Sheriffs:
  • Jeanne Boyarsky
  • Tim Cooke
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • salvin francis
  • Frits Walraven
Bartenders:
  • Scott Selikoff
  • Piet Souris
  • Carey Brown

using reflection to get getter of field?

 
Ranch Hand
Posts: 141
  • Mark post as helpful
  • send pies
  • 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: 21997
107
Eclipse IDE Spring VI Editor Chrome Java Ubuntu Windows
  • Mark post as helpful
  • send pies
  • 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
  • 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
  • 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...!)
 
If we don't do the shopping, we won't have anything for dinner. And I've invited this tiny ad:
Thread Boost feature
https://coderanch.com/t/674455/Thread-Boost-feature
    Bookmark Topic Watch Topic
  • New Topic