简体   繁体   English

Intellij 12.1中的自定义设置器

[英]custom setters in Intellij 12.1

I have a class with some 20 properties. 我有一堂课,有大约20个属性。 The setters should throw an exception if the property is not null. 如果属性不为null,则设置方法应引发异常。 Something like below 像下面这样

public void setLastname(String lastname) {
 if(this.lastname!=null)
    throw new IlegalArgumentException("lastname already set");
 this.lastname=lastname;
}

How can I auto generate such setters in IntelliJ? 如何在IntelliJ中自动生成此类设置程序?

IntelliJ IDEA has no way to customize getter/setter templates, vote for this request . IntelliJ IDEA无法自定义getter / setter模板,请对此请求进行投票

A workaround would be to create a Surround live template . 一种解决方法是创建一个环绕声实时模板 This way you can type the variable, like lastname , then select it and invoke Surround template that will convert the selection into 这样,您可以输入变量,例如lastname ,然后选择它并调用Surround模板,该模板会将选择内容转换为

public void setLastname(String lastname) {
 if(this.lastname!=null)
    throw new IlegalArgumentException("lastname already set");
 this.lastname=lastname;
}

Refer to the documentation for details. 有关详细信息,请参阅文档

You can create a live template: 您可以创建一个实时模板:

http://www.jetbrains.com/idea/webhelp/creating-and-editing-live-templates.html http://www.jetbrains.com/idea/webhelp/creating-and-editing-live-templates.html

This should work like: 它应该像这样工作:

public void set$CAP_SELECTION$(String $SELECTION$) {
 if(this.$SELECTION$!=null)
    throw new IlegalArgumentException("$SELECTION$already set");
 this.$SELECTION$=$SELECTION$;
}

You just write: 您只需写:

lastname, select the test and use the template 姓氏,选择测试并使用模板

CAP_SELECTION is a variable in kind of capitalize($SELECTION) CAP_SELECTION是大写形式的变量($ SELECTION)

I have created a template to generate setters which are generated with some customisation. 我已经创建了一个模板来生成通过一些定制生成的setter。 My setter function first checks if the argument is not null and then only sets to the output. 我的setter函数首先检查参数是否不为null,然后仅设置为输出。 You can generate similar templates in intellij. 您可以在intellij中生成类似的模板。 While you are generating the setter click the [...] button and create a new custom template. 在生成设置器时,单击[...]按钮并创建一个新的自定义模板。 Just for reference I am putting down my template gist link. 仅供参考,我放下了我的模板要点链接。

Template for generating setter with checking not null in IntelliJ Idea 用于在IntelliJ Idea中检查不为null的setter的模板

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM