如何为字段编写自定义注释,为该字段创建自定义设置器?

问题描述 投票:1回答:1

我有下课。

public class X {
    private int a1;
    private int a2;
    private int a3;
    private int a4;
    .
    .
    .
    private int a100;
    // name of fields are different in actual class(but there are sure 100 fields)
}

现在我不想将负值分配给任何int字段。所以为了做到这一点,我必须为所有这些编写setter(它将为所有字段编写setter(它只会设置正值))。

那么有没有办法可以减少我的努力,例如编写自定义注释(将为该字段生成setter,setter必须只设置正值并忽略nagative值)并将该annonation应用于所有字段。

在研究“如何在java中编写自定义注释”时,我发现我们可以为字段编写注释(为该字段指定默认值),对于方法,但是没有为“将为其创建setter的字段的自定义注释”田”。

注意: - 我也查看了lombok setter,但它只生成普通的setter,而不是我想要的自定义setter。

java annotations getter-setter lombok
1个回答
2
投票

如果您使用的是IntelliJ IDEA,则可以为此添加新的setter模板。

将光标放在您的班级,然后转到代码 - >生成。在菜单中,选择“Setter”。然后点击此菜单右上角的“...”:

enter image description here

然后,您可以使用以下代码添加名为“no negatives”的新模板:

#set($paramName = $helper.getParamName($field, $project))
#if($field.modifierStatic)
static ##
#end
void set$StringUtil.capitalizeWithJavaBeanConvention($StringUtil.sanitizeJavaIdentifier($helper.getPropertyName($field, $project)))($field.type $paramName) {
  if ($paramName >= 0) {
  #if ($field.name == $paramName)
    #if (!$field.modifierStatic)
      this.##
    #else
      $classname.##
    #end
  #end
    $field.name = $paramName;
  } else {
    throw new IllegalArgumentException("$paramName must be positive");
  }
}

请注意,此模板不会检查字段类型是否可以与0进行比较。

我基本上通过添加if语句修改了IntelliJ默认模板:

if ($paramName >= 0) {

和其他分支:

  } else {
    throw new IllegalArgumentException("$paramName must be positive");
  }

如果您只想在参数为负数时不设置字段,而不是抛出异常,只需删除else分支即可。

© www.soinside.com 2019 - 2024. All rights reserved.