vendredi 24 avril 2020

Using Reflection inside stream intermediate operations in Java

public class A {
    private List<B> listOfB = new LinkedList<>();
    //getter setters
}


public class B {
        private BigDecimal fieldOne;
        //8 more BigDecimal fields like this...
        private BigDecimal fieldTen;
        //getter setters
    }

I have a list of A objects and there I aimed to get sum of each fields of B objects to show it on a JSF page.

At first I thought to write ten methods like getSumOfFieldOne() ... getSumOfFieldTen() etc. in Class A. Then I thought maybe there could be a shorter way to do it.

I tried to use Reflection:

  public BigDecimal getSumOfField(String fieldName) throws Exception {
        Method getter = A.class.getMethod(String.format("get%s", StringUtils.capitalize(fieldName)));
        return getListOfB().stream()
               .map((BigDecimal)getter.invoke(A.class))
               .reduce(BigDecimal.ZERO, (d1, d2) -> d1.add(d2));
    }

and on JSF Page:

 <h:outputText value="#{theController.listOfA.getSumOfField('fieldOne')}"/>
  ...
 <h:outputText value="#{theController.listOfA.getSumOfField('fieldTen')}"/>

But it was not successful at compile time due to .map((BigDecimal)getter.invoke(A.class)) in getSumOfField

Writing 10 methods for each field or collecting the sum of these fields in a map in Class A are another options which I normally use in other cases. But I would like to try reflection way as it is more interesting and challenging. Could you please help me?

Thanks in advance.





Aucun commentaire:

Enregistrer un commentaire