0

Suppose I have class Foo which contains several fields of type String. Is there a way which I can iterate over each of these fields for a given Foo object and map a String function to each? I am looking for a solution which uses a lambda expression, something like the following:

Foo bar = new Foo(field1, field2, field3);
//here is where I am unsure 
bar.forEachField( field -> someFunc(field));

I am having trouble finding an example which goes through the fields of an object as opposed to some collection. I have tried to add each field to an ArrayList and then use replaceAll() on each String, but since each String is immutable this will have no affect on my actual Foo object.

sreisman
  • 658
  • 3
  • 9
  • 24
  • This seems like an X Y problem. I have never heard of someone wanting to do something like this. What are you actually trying to do (ie what is your suggested solution trying to solve)? – Bohemian Jun 24 '16 at 21:40
  • Why use reflection? All you need is `Stream.or(bar.field1, bar.field2, bar.field3).forEach(field -> someFunc(field))`. – JB Nizet Jun 24 '16 at 21:41
  • @JBNizet I am looking for something like this, thank you. My goal is to create objects which have fields that may need to be changed in the future according to specific rules, i.e. certain characters may need to be removed from each field. I would like a way to do this cleanly. – sreisman Jun 24 '16 at 21:46
  • I think you need [field.set()](https://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Field.html#set-java.lang.Object-java.lang.Object-) to replace the immutable object. Not sure if that's what you want to achieve your lambda... – Linus Jun 24 '16 at 22:04

0 Answers0