• 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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Use reflection to populate fields

 
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi:
Thanks for clicking in. I have a question on how to use reflection to populate the public fields in an object.
For example:


If I have tons of such fileds in an object that I will have to fill data in, is there any way not to manully populate them by using reflection? Thank you very much.
 
author and iconoclast
Posts: 24207
46
Mac OS X Eclipse IDE Chrome
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,

I don't see any public fields here, and I see setXXX methods for all the private fields. What's the problem, exactly?
 
(instanceof Sidekick)
Posts: 8791
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I'm guessing you get name value pairs like "age,21" from a flat file or database query where column name == field name?

Look at the javaDoc for Class.getMethods(). You could look for a method called "setAge", try to cast your value to the type expected by the method and invoke it.

I would probably only do this in a persistence framework or a boundary between Java and something not-Java like XML. For regular hand-made Java objects I'd call the setAge() method the usual way.
 
author
Posts: 284
35
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Let's say, for the sake of the argument, that your properties for a given object are inserted in a map. Maybe your read them from a configuration file and built up a map like this:
Map<String, Object> props = new HashMap<String, Object>();
props.put("name", "Harry Hacker");
props.put("age", 45); // autoboxing

Use this code outline:



Cheers,

Cay
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic