Generate `Objects.requireNonNull` lines for each argument automatically in IntelliJ?
Asked Answered
T

1

5

Might there be a way in IntelliJ 2018 to auto-generate the lines of code checking for null values passed in any argument?

I want IntelliJ to change this:

// ----------|  Constructor  |-----------------------------------
public DailyProduct ( LocalDate localDate , String name , Integer quantity ) {
    this.localDate = localDate;
    this.name = name;
    this.quantity = quantity;
}

…to this:

// ----------|  Constructor  |-----------------------------------
public DailyProduct ( LocalDate localDate , String name , Integer quantity , BigDecimal quality , BigDecimal realmq , BigDecimal cost ) {
    Objects.requireNonNull( localDate );  // ⬅ Generate these checks for null values.
    Objects.requireNonNull( name );
    Objects.requireNonNull( quantity );

    this.localDate = localDate;
    this.name = name;
    this.quantity = quantity;
}

Even better would be if IntelliJ could write all the argument-to-member assignments and use the Objects.requireNonNull. So this:

// ----------|  Constructor  |-----------------------------------
public DailyProduct ( LocalDate localDate , String name , Integer quantity , BigDecimal quality , BigDecimal realmq , BigDecimal cost ) {
}

…would become this:

// ----------|  Constructor  |-----------------------------------
public DailyProduct ( LocalDate localDate , String name , Integer quantity ) {
    this.localDate = Objects.requireNonNull( localDate );  // ⬅ Generate all these lines entirely.
    this.name = Objects.requireNonNull( name );
    this.quantity = Objects.requireNonNull( quantity );
}
Tanaka answered 5/1, 2019 at 0:0 Comment(3)
You can create a Live Template to do that.Chipman
Do you have a good reason not to want to use the return value? this.localDate = Objects.requireNonNull(localDate);?Concentration
@AndyTurner Oh, yes, even better. I never noticed that return value. Thanks! Editing the Question now to reflect that.Tanaka
D
6

You could try the following:

In Settings / Live template create a new live template

enter image description here

define the $content$ variable with [Edit Variables]:

enter image description here

with the following groovyScript:

groovyScript("def params = _1.collect { 'this.' + it + ' = Objects.requireNonNull(' + it + ');' }.join(); params", methodParameters());

now when you use the abbreviation

enter image description here

you should get the following

enter image description here

Let me know if it helps.

Dessert answered 5/1, 2019 at 8:19 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.