Win a copy of Machine Learning Systems: Designs that scale this week in the Scala forum
or Xamarin in Action: Creating native cross-platform mobile apps in the Android forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Looping though get methods without using reflection  RSS feed

 
Ranch Hand
Posts: 323
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a POJO that I want to convert into a HashMap. Now in the past, I've done the following.



And it works, but it's a pain to create and needs to be updated any time a field changes.

What I'd like to be able to do is loop through all of the get methods, automatically placing them in as key/value pairs. I know you can do this with reflection, but is there an easier, less resource intensive way to do it?

TIA.
 
Ranch Hand
Posts: 37
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes it is possible. I previously did something quite similar.



I basically copied and pasted this from my code so let me know if you have any questions or it doesn't work quite right.
 
Sheriff
Posts: 21330
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
But that's not without using reflection.

But alas, it's simply not possible without it. You need to inspect the class to find out which methods there are, and reflection is the only way.
 
Bai Shen
Ranch Hand
Posts: 323
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yeah, I didn't think it was possible, but I thought I'd ask. I was hoping to avoid a reflection performance hit.
 
Jarred Olson
Ranch Hand
Posts: 37
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Rob Prime wrote:But that's not without using reflection.



True (and reflection sucks to debug/maintain), but the implementation is pretty straightforward. One thing you could do is implement a toHashMap() method which builds a HashMap of the current object. Downside of that is that you'd have to implement it in every class you want that functionality and consistently update it (something you already mentioned). If you've written a bunch of code already then it would suck, but if you're just starting out it wouldn't be to bad. Just like unit testing... update the class update the test/HashMap method.
 
Author
Rancher
Posts: 12617
IntelliJ IDE Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
IIRC Apache Commons already has this functionality; can't think of where off the top of my head.
 
Are you okay? You look a little big. Maybe this tiny ad will help:
Rocket Oven Kickstarter - from the trailboss
https://coderanch.com/t/695773/Rocket-Oven-Kickstarter-trailboss
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!