Friends of OpenJDK Today

Generating Code with IntelliJ IDEA

February 10, 2021

Author(s)

  • Helen Scott

    Helen is a Java Developer Advocate at JetBrains. She has over 20 years’ experience in the software industry which has been gained in a variety of roles including developer, technical ... Learn more

One of the super cool things about IntelliJ IDEA is how much code you can generate with minimum effort. Yes, it's not the 1990s anymore, we're no longer measured on how many lines of code we generate (thankfully), but you also know that Java has its fair share of boilerplate code.

Well, there's a shortcut in IntelliJ IDEA that generates a lot of code for you:

  • ⌘N on macOS
  • Alt+Insert on Windows and Linux

These shortcuts load the Generate menu. Here's a quick tour of where you can use it in Java projects in IntelliJ IDEA. It’s not a complete list; let me know where else we can use it please!

New Java Class

In the Project Window, you can use this shortcut to create a whole host of things which are project and folder specific. If you use the shortcut on your directory that is marked as your sources root (usually src) in a Java project you get the option to create a new Java file (among other things). You're then asked to select between a Class, Interface, Record (Preview), Enum or Annotation. It's a speedy way of creating new classes for your project.

Before we move on, a closely related shortcut is the one we use for a new Scratch File. It's ⌘⇧N on macOS, or Ctrl+Shift+Alt+Ins on Windows/Linux. You can select to create a new Scratch file using ⌘N on macOS, or Alt+Ins on Windows and Linux in the Project Tool window, but it's worth committing the scratch file shortcut to memory too as it's handy to be able to dump some code or notes in an area outside your project and share it across IntelliJ IDEA projects.

Constructors

Now that you've got your class, you may want to generate a constructor or two. However, before we do that, let's add a couple of variables to our class:

public class GenerateCode {
   private final String name = "Helen";
   private int age;
   private String mood;
}

We can use the same shortcut to make ourselves a constructor. We get some options here because we've got some fields in our class:
Choose fields to initialize by construtor
IntelliJ IDEA is asking us if we want to pass our fields into our Constructor. If we select both and click OK we have our Constructor with the parameters passed in.

public class GenerateCode {
   private final String name = "Helen";
   private int age;
   private String mood;

   public GenerateCode(int age, String mood) {
       this.age = age;
       this.mood = mood;
   }
}

Other Class-Based Generate Options

We don't need to stop there either. There's a whole host of code that IntelliJ IDEA can generate for us at this stage including:

  • Getter
  • Setter
  • Getter and Setter
  • equals() and hashCode()
  • toString()
  • Override Methods
  • Delegate Methods
  • Test

While we're here, Java Records are coming and IntelliJ IDEA is ready. Another way you could generate code if you're not ready to move to Java Records is to use the Generate shortcut to create a new Java record, and then you can convert the Java record to a normal Java class with ⌥⏎ on macOS, or Alt+Enter on Windows and Linux with your caret on the class name.

Implement Methods

When our Java class implements an interface, we need to ensure that we implement that interface's methods. The Generate menu helps us here too. Let's say that our code looks like this, and we're implementing NewInterface:

public class GenerateCode implements NewInterface {
   private final String name = "Helen";
   private int age;
   private String mood;
}

When we use ⌘N on macOS, or Alt+Insert on Windows and Linux this time, we see select a new option call Implement Methods:
Select methods to implement

The keyboard shortcut is ⌃I on macOS, or Ctrl+I on Windows/Linux. This allows you to generate the code required to implement the methods in the Java interface that we're implementing with the @Override annotation.

Now IntelliJ IDEA has generated that code for us:

public class GenerateCode implements NewInterface {
   private final String name = "Helen";
   private int age;
   private String mood;

   @Override
   public void doSomething() {
   }

   @Override
   public void goSomewhere() {
   }
}

This also works for overriding methods from superclasses/super abstract classes.

Add Parameters / Arguments

Another useful trick you so is to use ⌘N on macOS, or Alt+Insert on Windows and Linux when you're in a dialogue, and you need to add more rows or data. For example, we added a default constructor to our class, but we now want to refactor it to change the signature. Our code currently reflects the default constructor:

public class GenerateCode{
   private final String name = "Helen";
   private int age;
   private String mood;

   public GenerateCode() {
   }
}

Let's refactor the Constructor with ⌘F6 on macOS, or Ctrl+F6 on Windows/Linux. In the Change Signature dialogue, you can use ⌘N on macOS, or Alt+Insert on Windows/Linux to add a new parameter. This saves you using your mouse to click the little + icon.

This trick works in all the dialogue boxes that require additional lines to be added that I've found so far.

Generate Test Methods

Finally, everyone loves a good test and rightly so. We've already mentioned that you can use the Generate menu from a Java method to generate a corresponding test class. However, once you're in the test class, you can use ⌘N on macOS, or Alt+Insert on Windows and Linux again to create much of the boilerplate code you might need, including (for JUnit5 at least):

  • Test Method
  • SetUp Method
  • TearDown Method
  • BeforeClass Method
  • AfterClass Method

If you are working with a different testing framework, your Generate menu will give you other relevant options.

Summary

Java may be a little clunky on the boilerplate side of things, but IntelliJ IDEA takes the heavy lifting out of that to a large extent so along with the shorcut for intention actions, it's a compelling combination.

Topics:

Related Articles

View All
  • Apple Silicon with Zulu OpenJDK and IntelliJ IDEA

    Azul has been leading the OpenJDK community effort (JEP 391) initiated in August 2020 to add support for Apple Silicon, Arm-based Macs, in future versions of OpenJDK.

    In addition to targeting future Java versions, such as Java 16 via JEP 391, Azul has made OpenJDK builds of currently popular Java versions, including Zulu builds of OpenJDK 8, 11, and 13, as well as 16-ea, widely available for use on Apple Silicon, Arm-based Macs.

    Read More
    Avatar photo
    November 26, 2020
  • IntelliJ IDEA Made Me Lazy

    I haven’t always been lazy; it’s a fairly recent addition to my repertoire of skills. And do you know who I blame? I blame IntelliJ IDEA. I used to check that I’d completed a statement correctly, I used to look at javadoc, I used to check I’d closed my parentheses correctly, but now I don’t give things a second glance.

    Being lazy isn’t a bad thing, it’s an efficiency gain that allows me to focus on the things that matter, which isn’t checking my parentheses are correct or remembering to put a semi-colon after my statement. No, it’s taking time for myself and those around me. Sure, it’s IntelliJ IDEA’s fault, but I am happy that we’re here!

    Read More
    November 24, 2020
  • Live Templates in IntelliJ IDEA

    When I first came across the notion of Live Templates, I couldn’t figure out what was ‘live’ about them. Did they need feeding or something?

    It seems to be an industry-standard term, so I’m no longer devoting much energy to this quandary, but if you were wondering the same, you’re not alone.

    Read More
    October 26, 2020

Author(s)

  • Helen Scott

    Helen is a Java Developer Advocate at JetBrains. She has over 20 years’ experience in the software industry which has been gained in a variety of roles including developer, technical ... Learn more

Comments (0)

Your email address will not be published. Required fields are marked *

Highlight your code snippets using [code lang="language name"] shortcode. Just insert your code between opening and closing tag: [code lang="java"] code [/code]. Or specify another language.

Save my name, email, and website in this browser for the next time I comment.

Subscribe to foojay updates:

https://foojay.io/feed/
Copied to the clipboard