KikeSP
KikeSP

Reputation: 103

Initialize objects with Lombok

I have the following object:

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public class MyComplexObject implements Serializable {
        private static final long serialVersionUID = 1L;
        private OuputObject ouput;
    }

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public class OuputObject implements Serializable {
        private static final long serialVersionUID = 1L;
        private InputObject input;
    }

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public class InputObject implements Serializable {
        private static final long serialVersionUID = 1L;
        private List<String> example;
    }

When instantiating the object, the object is not initialized "OuputObject" and is always NULL. Why is the OuputObject object and the InputObject object not instantiated or initialized?

When I do a: getInputObject () I get a NullPointerException

(This is an example, it's fake data)

Upvotes: 1

Views: 5403

Answers (2)

name not found
name not found

Reputation: 622

Lombok doesn't initialize properties. The annotation @Data only generates getters and setters for the class properties and overrides the toString, hashCode and equals method.

@Data
public class MyClass {
    private String myString;
}

Generates the following code:

public class MyClass {
    private String myString;

    public String getMyString() {
        return myString;
    }

    public void setMyString(String myString) {
        this.myString = myString;
    }

    // equals, hashcode, toString
}

Have a look at the documentation

Upvotes: 2

menteith
menteith

Reputation: 678

@Data creates getters and setter, @AllArgsConstructor creates constructor for all the fields, and @NoArgsConstructor creates default constructor. To have your object initialised, you need to use constructor, e.g.

MyComplexObject mco = new MyComplexObject(new InputObject());

Upvotes: 2

Related Questions