Win a copy of Java 9 Modularity: Patterns and Practices for Developing Maintainable Applications this week in the Java 9 forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Looping though get methods without using reflection  RSS feed

 
Bai Shen
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.
 
Jarred Olson
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.
 
Rob Spoor
Sheriff
Posts: 21114
85
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.
 
David Newton
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.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!