Is there a way to parameterize a method name?
Example:
JournalLine {
BigDecimal ccyAmount;
BigDecimal lcyAmount;
BigDecimal rptAmount;
// Getters and Setters
}
Original (working)
// Calculate totals
BigDecimal totalCcyAmount = journalLines.stream()
.map(journalLine -> journalLine.getCcyAmount())
.reduce((a, b) -> a.add(b))
.orElse(BigDecimal.ZERO);
BigDecimal totalLclAmount = journalLines.stream()
.map(journalLine -> journalLine.getLclAmount())
.reduce((a, b) -> a.add(b))
.orElse(BigDecimal.ZERO);
BigDecimal totalRptAmount = journalLines.stream()
.map(journalLine -> journalLine.getRptAmount())
.reduce((a, b) -> a.add(b))
.orElse(BigDecimal.ZERO);
This duplication is used in different locations of the application. Not always together.
Is there a way to do something like:
//Calculate totals and pass the method name
BigDecimal totalCcyAmount = getTotal(journalLines, "getCcyAmount");
BigDecimal totallclAmount = getTotal(journalLines, "getCcyAmount");
BigDecimal totalRptAmount = getTotal(journalLines, "getCcyAmount");
public BigDecimal getTotal( List<JournalLine> journalLines, String METHOD_NAME) {
return journalLines.stream()
.map(journalLine -> journalLine.METHOD_NAME)
.reduce((a, b) -> a.add(b))
.orElse(BigDecimal.ZERO);
}
I want to pass METHOD_NAME (getCcyAmount() or getLcyAmount() or getRptAmount ()) or use a different approach to avoid duplication of code.