Useful IntelliJ plugins for java developers 2 (Lombok)

1. Introduction

Today, I would show you the useful IntelliJ IDEA plugin for java developers : the Lombok plugin.

2.1 The Lombok plugin introduction

the_lombok_project

  • The plugin description
    • This plugin provides support for lombok annotations to write great Java code with IntelliJ IDEA.
  • The plugin official site

2.2 How to install this plugin

  • Install the plugin online:
    • Preferences > Plugins > Browse repositories… > Search for “lombok”
  • Install Plugin Manually:
    • Download the latest release and install it manually using Preferences > Plugins > Install plugin from disk…
  • Restart IDE.

2.3 How to use this plugin

2.3.1 Set the lombok dependency in your project

  • for maven users In your pom.xml:
<dependencies>
	<dependency>
		<groupId>org.projectlombok</groupId>
		<artifactId>lombok</artifactId>
		<version>1.16.20</version>
		<scope>provided</scope>
	</dependency>
</dependencies>
  • for gradel users In your build.gradle:
// 'compile' can be changed to 'compileOnly' for Gradle 2.12+

// or 'provided' if using 'propdeps' plugin from SpringSource

compile "org.projectlombok:lombok:1.16.20"

2.3.2 Change the IntelliJ IDEA preferences

In your project: Click Preferences -> Build, Execution, Deployment -> Compiler, Annotation Processors. Click Enable Annotation Processing.

Afterwards you might need to do a complete rebuild of your project via Build -> Rebuild Project.

2.4 The lombok annotations

2.4.1 The lombok @Getter/@Setter annotation

  • What does this annotation do?
    • You can annotate any field with @Getter and/or @Setter, to let lombok generate the default getter/setter automatically.
  • The official site for this annotation: site
  • The example usage code:
public class BoxGetterSetter {
    @Getter @Setter //declare this on field,there is no need to write getter/setters anymore

    private int width;
    @Getter @Setter
    private String label;

    public static void main(String[] args) {
        BoxGetterSetter box = new BoxGetterSetter();
        box.setWidth(12);//just use the setter

        box.setLabel("a box");
        System.out.println(box.getLabel()+",width:"+box.getWidth());//just use the getter

    }
}
  • The output:
a box,width:12

2.4.2 The lombok @ToString annotation

  • What does this annotation do?
    • Any class definition may be annotated with @ToString to let lombok generate an implementation of the toString() method. By default, it’ll print your class name, along with each field, in order, separated by commas.
  • The official site for this annotation: site
  • The example usage code:
@ToString(of = {"area","width"})
public class BoxToString {
    private double area;
    private int height;
    private int width;
    @Getter @Setter
    private String label;

    public BoxToString(String label, int width, int height) {
        this.label = label;
        this.width = width;
        this.height = height;
    }

    public static void main(String[] args) {
        System.out.println(new BoxToString("aBox",2,3));
    }
}
  • The output:
BoxToString(area=0.0, width=2)

You can also use the exlude mode of the ToString annotation like this:

@ToString(exclude = {"area","height"})
public class BoxToString {...

The output is the same as the above.

2.4.3 The lombok @EqualsAndHashCode annotation

  • What does this annotation do?
    • Any class definition may be annotated with @EqualsAndHashCode to let lombok generate implementations of the equals(Object other) and hashCode() methods.
  • The official site for this annotation: site
  • The example usage code:
@EqualsAndHashCode(of = {"width","height"}) //line 1

public class BoxEqualsAndHashcode {
    private double area;
    private int height;
    private int width;
    @Getter
    @Setter
    private String label;

    public BoxEqualsAndHashcode(int width,int height) {
        this.width = width;
        this.height = height;
    }

    public static void main(String[] args) {
        BoxEqualsAndHashcode box1 = new BoxEqualsAndHashcode(1,2);
        BoxEqualsAndHashcode box2 = new BoxEqualsAndHashcode(1,2);
        System.out.println(box1.equals(box2));
    }
}

The line 1 means just generate hashCode and equals using the width and height field of the object.

  • The output:
true

You can also use the exlude mode of the EqualsAndHashCode annotation like this:

@EqualsAndHashCode(exclude = {"label","area"})
public class BoxEqualsAndHashcode {...

The output is the same as the above.

2.4.4 The lombok @RequiredArgsConstructor annotation

  • What does this annotation do?
    • @RequiredArgsConstructor generates a constructor with 1 parameter for each field that requires special handling.
  • The official site for this annotation: site
  • The example usage code:
@RequiredArgsConstructor
@ToString(of = {"height","width"})
public class BoxConstructor {
    private double area;
    private final int height;
    private final int width;
    private String label;

    public static void main(String[] args) {
        BoxConstructor box = new BoxConstructor(10,20);
        System.out.println(box);
    }
}

You can see that the height and width is final, so the lombok @RequiredArgsConstructor detect it and generate a constructor as follows:

public BoxConstructor(int height, int width) {…}

  • The output:
BoxConstructor(height=10, width=20)

2.4.5 The lombok @Log annotation

  • What does this annotation do?
    • You can annotate any class with a log annotation to let lombok generate a logger field.
  • The @Log features:
    • @CommonsLog
      • Creates private static final org.apache.commons.logging.Log log = - org.apache.commons.logging.LogFactory.getLog(LogExample.class);
    • @JBossLog
      • Creates private static final org.jboss.logging.Logger log = org.jboss.logging.Logger.getLogger(- LogExample.class);
    • @Log
      • Creates private static final java.util.logging.Logger log = java.util.logging.Logger.getLogger(- LogExample.class.getName());
    • @Log4j
      • Creates private static final org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger(- LogExample.class);
    • @Log4j2
      • Creates private static final org.apache.logging.log4j.Logger log = - org.apache.logging.log4j.LogManager.getLogger(LogExample.class);
    • @Slf4j
      • Creates private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(- LogExample.class);
    • @XSlf4j
      • Creates private static final org.slf4j.ext.XLogger log = org.slf4j.ext.XLoggerFactory.getXLogger(LogExample.class);
  • The official site for this annotation: site
  • The example usage code:
@RequiredArgsConstructor //auto generate the Constructor

@ToString(of = {"height","width"}) // auto generate toString

@CommonsLog // auto generate the log field

public class BoxLog {
    private double area;
    private final int height;
    private final int width;
    private String label;

    public static void main(String[] args) {
        log.debug("start");
        BoxLog box = new BoxLog(10,20);
        log.info("box is "+box);
        log.info("end");
    }
}
  • The output:
21:54:11.071 [main] DEBUG java8.learn.lombok.BoxLog - start
21:54:11.086 [main] INFO java8.learn.lombok.BoxLog - box is BoxLog(height=10, width=20)
21:54:11.086 [main] INFO java8.learn.lombok.BoxLog - end

2.4.6 The lombok @Data annotation

  • What does this annotation do?
    • @Data is a shortcut for @ToString, @EqualsAndHashCode, @Getter on all fields, @Setter on all non-final fields, and @RequiredArgsConstructor.
  • The official site for this annotation: site
  • The example usage code:
@Data // auto generate toString/equals/hashCode/getter/setter/constructor on final fields

@CommonsLog
public class BoxData {
    private double area;
    private final int height;
    private final int width;
    private String label;

    public static void main(String[] args) {
        log.debug("start");
        BoxData box = new BoxData(10,20);
        log.info("box is "+box);
        BoxData box2 = new BoxData(10,20);
        log.debug(box.equals(box2));
        log.info("end");
    }
}
  • The output:
21:58:07.845 [main] DEBUG java8.learn.lombok.BoxData - start
21:58:07.850 [main] INFO java8.learn.lombok.BoxData - box is BoxData(area=0.0, height=10, width=20, label=null)
21:58:07.851 [main] DEBUG java8.learn.lombok.BoxData - true
21:58:07.851 [main] INFO java8.learn.lombok.BoxData - end

2.4.7 The lombok @Cleanup annotation

  • What does this annotation do?
    • You can use @Cleanup to ensure a given resource is automatically cleaned up before the code execution path exits your current scope. You do this by annotating any local variable declaration with the @Cleanup annotation.
  • The official site for this annotation: site
  • The example usage code:
@CommonsLog
public class BoxCleanUp {
    public static void main(String[] args) throws Exception {
        @Cleanup InputStream in = new FileInputStream("test-java8.log");
        @Cleanup OutputStream out = new FileOutputStream("b.txt");
        byte[] b = new byte[10000];
        while (true) {
            int r = in.read(b);
            if (r == -1) break;
            out.write(b, 0, r);
        }
    }
}

3. Summary

The Lombok plugin helps you to generate some boilertemplate code for you , it can improve your efficiency. I recommend use it.

Other similar posts about IntelliJ IDEA plugins: