IntelliJ IDEA 2016.2 Help

Generating Getters and Setters

On this page:

Introduction

You can generate accessor and mutator methods (getters and setters) for the fields of in your classes. IntelliJ IDEA generates getters and setters with only one argument, as required by the JavaBeans API.

The getter and setter method names are generated by IntelliJ IDEA according your code generation naming preferences.

In the PHP context, getters and setters are generated using the PHP getter/setter file template. By default, as specified in these templates, setters are generated with the set prefix and getters with the set or get prefix according to the inferred field type boolean or con-boolean. The prefix is the value of the ${GET_OR_IS} variable in the default getter template. The default template is configured in the Code tab on the File and Code Templates page of the Settings / Preferences Dialog.

Generating accessor and mutator methods

  1. On the main menu, choose Code | Generate.
    Alternatively, right-click the editor and choose Generate on the context menu, or use Alt+Insert keyboard shortcut.
  2. In the pop-up list that is displayed in the editor, select one of the following options:
    • Getter: Accessor methods for getting the current values of the fields that will be selected in the Choose Fields to Generate Getters and Setters dialog box.
    • Setter: Mutator methods for setting specified values to the fields.
    • Getter and Setter: Both methods.
  3. In the Choose Fields to Generate Getters and Setters dialog box, select the fields to generate getters or setters for.

    You can add a custom setter or getter by clicking browseButton and accessing Getter/Setter Templates dialog. If getters and setters for a field already exist, this field is not included in the list.

  4. Click OK when ready.

Example 1

Consider the following code:

public class MyClass { int aInteger; }

In the Naming section of the Code Generation page, parameter prefix is set to my, and parameter suffix to Param.

After generating the getter and setter the following code will be produced:

public class MyClass { int aInteger; public int getAInteger() { return aInteger; } public void setAInteger (int myAIntegerParam) { aInteger = myAIntegerParam; } }

Example 2

However, if a is specified as a field prefix in the Code Generation page, then it will not take part in the generation of the method and parameter names:

public class MyClass { int aInteger; public int getInteger() { return Integer; } public void setInteger (int myIntegerParam) { aInteger = myIntegerParam; } }

See Also

Last modified: 5 September 2016