Java bean: The fastest way to implement an element iterator?

I have a standard Java bean, MyJavaBean. Let's say it has 50 variables, and I created 50 getters and 50 setters with an eclipse.

This bean is filled with some pipeline business logic, and now I want to go through all 50 elements. For example, to implement the string method. Naturally, I do not want to call each method getter.

Now there are some obvious but lengthy approaches:

  • we implement a bean so that it keeps the set of its elements up to date as soon as it goes, and then just write getter for this

  • manually implement an iterator by adding each item to the collection and returning that

I have two questions:

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

  • How can I make it smarter? Is there any library that will return a collection of elements based on a JavaBean using reflection or something similar?

+4
source share
2 answers

If your class is a JavaBean, I would advise you not to access the fields directly; instead, I would use the JavaBeans / BeanInfo mechanism. You can do this either Introspectordirectly or through a helper library like Apache Commons / BeanUtils or SpringBeanWrapper abstraction.

Check this previous answer for reference:

Java Reflection: how can I get all getter methods of the java class and call them

+1
source

-. , -, HashMap, . , , .

Java, .

, Class.getFields :

   Field[] fields = MyJavaBean.class.getFields();
   for (Field field : fields)
   {
       System.out.println ("Field: " + field.getName());
   }
0

Source: https://habr.com/ru/post/1525410/


All Articles