lundi 11 octobre 2021

Take values from Object class object to POJO class object

I have a non-entity object, for simplicity here, lets say it has 3 fields with getters and setters and constructor(in real app it has more fields but it's not important now):

import java.math.BigDecimal;
import java.time.LocalDate;

public class TotalPerDayDTO
{
    private BigDecimal thirdShift;
    private BigDecimal firstShift;
    private BigDecimal secondShift;
    
    public TotalPerDayDTO(BigDecimal thirdShift, BigDecimal firstShift, BigDecimal secondShift)
    {
        this.thirdShift = thirdShift;
        this.firstShift = firstShift;
        this.secondShift = secondShift;
    }

    public BigDecimal getThirdShift()
    {
        return thirdShift;
    }

    public void setThirdShift(BigDecimal thirdShift)
    {
        this.thirdShift = thirdShift;
    }

    public BigDecimal getFirstShift()
    {
        return firstShift;
    }

    public void setFirstShift(BigDecimal firstShift)
    {
        this.firstShift = firstShift;
    }

    public BigDecimal getSecondShift()
    {
        return secondShift;
    }

    public void setSecondShift(BigDecimal secondShift)
    {
        this.secondShift = secondShift;
    }
}

After query (which sums values from different enities) I've got Object result = query.getSingleResult();

For example, if I get [10,0,10] values in my result object, I want to use those values as arguments for TotalPerDayDTO constructor.

I've tried reflection and introspection before, nothing works (nor I understand reflection clearly). I've tried this: Java how to work with getDeclaredField("someVaraible") method And here Charlie's answer: Java reflection: how to get field value from an object, not knowing its class





Aucun commentaire:

Enregistrer un commentaire