在IntelliJ中自动生成`Objects.requireNonNull`代码行以检查每个参数?

5

在IntelliJ 2018中是否有一种方法可以自动生成检查任何参数传递的空值的代码行?

我希望IntelliJ更改这个:

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

…变成这样:

// ----------|  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;
}

更好的情况是,如果IntelliJ可以编写所有参数到成员分配,并使用Objects.requireNonNull。所以这样:
// ----------|  Constructor  |-----------------------------------
public DailyProduct ( LocalDate localDate , String name , Integer quantity , BigDecimal quality , BigDecimal realmq , BigDecimal cost ) {
}

…会变成这样:

// ----------|  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 );
}

你可以创建一个Live Template来实现这个功能。 - Andreas
3
你有什么好的理由不想使用返回值吗?this.localDate = Objects.requireNonNull(localDate); - Andy Turner
@AndyTurner 哦,是的,更好了。我从来没有注意到返回值。谢谢!现在正在编辑问题以反映这一点。 - Basil Bourque
1个回答

6
你可以尝试以下操作:
在“设置/实时模板”中创建一个新的实时模板。

enter image description here

使用[编辑变量]定义$content$变量:

enter image description here

使用以下groovyScript:

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

现在,当您使用缩写时

enter image description here

你应该得到以下内容

enter image description here

让我知道是否有帮助。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接