Reputation: 827
I have a class with some 20 properties. The setters should throw an exception if the property is not 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?
Upvotes: 2
Views: 1900
Reputation: 1223
I have created a template to generate setters which are generated with some customisation. My setter function first checks if the argument is not null and then only sets to the output. You can generate similar templates in 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
Upvotes: 0
Reputation: 16060
You can create a live template:
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)
Upvotes: 3
Reputation: 401975
IntelliJ IDEA has no way to customize getter/setter templates, vote for this request.
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
public void setLastname(String lastname) {
if(this.lastname!=null)
throw new IlegalArgumentException("lastname already set");
this.lastname=lastname;
}
Refer to the documentation for details.
Upvotes: 3