Skip to content
Advertisement

@Data annotion not working to set the value in Java

I have this POJO class:

import lombok.Data;
import lombok.Getter;
import lombok.Setter;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import java.io.Serializable;

@Data
@XmlAccessorType(XmlAccessType.FIELD )
public class FulfillmentOrder implements Serializable {

    private static final long serialVersionUID = 1L;

    @XmlElement(name="orderNbr")
    Integer orderNbr;

    public Integer setOrderNumbr(Integer orderNbr) {
        this.orderNbr=orderNbr;
        return orderNbr;
    }
}

I am trying to set the value of orderNbr from a different class.

FulfillmentOrder fo= new FulfillmentOrder();
Integer orderNum = 
  fo.setOrderNumbr(89898989);

I am trying to update the value of orderNbr in my XML output to 89898 and I want to do it using @Data.

But when I am doing fo.setOrderNbr(89898989)I am getting a compile time error as Error:(56, 132) java: incompatible types: void cannot be converted to java.lang.Integer, since lombok returns void.

Any way of `fo.setOrderNbr(89898989) to update the value?

Advertisement

Answer

Your problem is that your class effectively has two methods with the same signature. Signature of a method is its name + parameters. So in your case setOrderNbr(Integer orderNbr). Return type is not included in the signature.

As explained in Javadoc it is a compile time error to have methods with identical signature in the same class. https://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.4.2

For you to allow Lombok to do the work – you need to delete your method setOrderNbr(Integer orderNbr) and call the Lombok generated setter that comes from @Data. It will have the same name but no return type in accordance with usual coding practices.

If you insist on having a setter with a return type you will have to define it yourself but it has to have a different signature – in your case a different name to not clash with the one that Lombok generates with @Data.

Advertisement