Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IntelliJ getter/setter format (single-line versus multi-line)

How can you get IntelliJ to generate getter/setters accessor methods on one line like this:

public String getAbc() { return abc; } 

… instead of multiple lines like this:

public String getAbc() {    return abc; } 
like image 425
Marcus Leon Avatar asked Nov 23 '09 18:11

Marcus Leon


People also ask

What is the difference between setter and getter?

Getters and setters are used to protect your data, particularly when creating classes. For each instance variable, a getter method returns its value while a setter method sets or updates its value. Given this, getters and setters are also known as accessors and mutators, respectively.

What is the data type for getter and setter methods?

Getter and Setter are methods used to protect your data and make your code more secure. Getter returns the value (accessors), it returns the value of data type int, String, double, float, etc. For the program's convenience, getter starts with the word “get” followed by the variable name.

Should you always have getters and setters?

Using getters and setters, is always, in my opinion good practice. One thing you should avoid is to have external entities mess with the internal structure of your class at will. Typical example, consider having a dateOfBirth parameter.


1 Answers

I'm using IntelliJ IDEA 14.1.0 and you can customise this behaviour.

Just use the "Generate..." option, or use Alt+Insert shortcut, and select "Getter and Setter".

In the "Select Fields" window that gets opened, you have the "Getter Template" option at the top. Use the "..." button next to the dropdown, to edit the template.

Select "IntelliJ Default" and click the "Copy" button to create a new one named "AlwayStartWithGet", which you can edit.

Just remove the following section:

#if ($field.boolean)   #if ($StringUtil.startsWithIgnoreCase($name, 'is'))     #set($name = $StringUtil.decapitalize($name))   #else     is## #end #else   get## #end 

And replace it with a simple

get## 

You should be left with:

public ## #if($field.modifierStatic)   static ## #end $field.type ## #set($name = $StringUtil.capitalizeWithJavaBeanConvention($StringUtil.sanitizeJavaIdentifier($helper.getPropertyName($field, $project)))) get## ${name}() {   return $field.name; } 

Now you can use the custom template when generating code, by selecting it in the getter template dropdown.

like image 168
Alex G Avatar answered Sep 20 '22 11:09

Alex G