How can I get @getter and @setter?

Shapci picture Shapci · Mar 3, 2016 · Viewed 7.6k times · Source

I often see the following annotations in code:

@Getter
@Setter
public int test = 1;

I know I can create getter and setter methods using this annotations. But which classes/library do I need to use these annotations?

Answer

Jordi Castilla picture Jordi Castilla · Mar 3, 2016

@Getter and @Setter are Lombok annotations.


Lombok is a framework that generates repetitive code like, equals, hashCode() or getters and setters in annotated classes or attributes, cleaning up the code, making coding much faster and avoiding human errors because of forgetting some parts...

Just note one thing: your attribute is public, what has not much sense when you insert getters and setters:

@Getter
@Setter
private int test = 1;

Is the equivalent to:

private int test = 1;

public int getTest() {
    return test;
}

public void setTest(int test) {
    this.test = test;
}

How to get Lombok into your project:

  • If you use Eclipse / NetBeans download here the jar and add it to your project following the instructions.
  • IntelliJ has it's own Plugin by Michail Plushnikov:
  • Maven

    <dependencies>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.6</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>
    
  • Other repositories services (Ivi, SBT, Graddle) check here