4

I have a bog-standard Java bean, MyJavaBean. Say it has 50 variables, and I have generated 50 getters and 50 setters with eclipse.

This bean is populated by some assembly line of business logic, and now I want to traverse all 50 elements. For example, to implement a to-string method. Naturally I don't want to call each getter method.

Now there are some obvious but long approaches:

  • implement the bean so that it keeps a collection of it's elements up to date as it goes, then just write a getter for that

  • manually implement an iterator by adding each element to a collection and returning that

So I have two questions:

  • if I have a bean with 50 elements, have I already made a mistake? Is this a negative pattern?

  • How can I do this in a cleverer way? Is there some library that will return a collection of elements given a JavaBean, using reflection or something similar?

Tony the Pony
  • 40,327
  • 71
  • 187
  • 281
Paul
  • 3,318
  • 8
  • 36
  • 60

2 Answers2

1

If your class is a JavaBean, I'd advise against accessing the fields directly, instead I'd use the JavaBeans / BeanInfo mechanism. You can do that either by using the Introspector directly or through a helper library like Apache Commons / BeanUtils or Spring's BeanWrapper abstraction.

Check this previous answer of mine for reference:

Java Reflection: How can i get the all getter methods of a java class and invoke them

Community
  • 1
  • 1
Sean Patrick Floyd
  • 292,901
  • 67
  • 465
  • 588
  • This might not be the fastest in terms of runtime but in terms of implementation time. – SpaceTrucker Feb 05 '14 at 13:19
  • @SpaceTrucker as usual, before optimizing, find out if you actually have a bottleneck (through profiling etc.). Before you've identified a bottleneck, you might as well use the high level approach – Sean Patrick Floyd Feb 05 '14 at 13:56
  • For the sake of completeness, the solution I used in the end was: Map properties = BeanUtils.describe(MyJavaBean); List list = new ArrayList(properties.values()); for(Object obj : list) { /*my logic*/ } – Paul Feb 06 '14 at 11:32
0

It does smell like an anti-pattern. If your class only contains data, and no business logic, you might be better off implementing a HashMap-based data structure, especially if the data fields are likely to change in the future. However, without knowing your project's requirements, it's difficult to tell.

You can always iterate through the fields of a plain old Java class using reflection.

In particular, use the Class.getFields method to determine the fields of a given class:

   Field[] fields = MyJavaBean.class.getFields();
   for (Field field : fields)
   {
       System.out.println ("Field: " + field.getName());
   }
Tony the Pony
  • 40,327
  • 71
  • 187
  • 281