Search code examples
javaeclipserefactoringthis

How to force Eclipse to use the this keyword when auto-generating getters and setters?


In Eclipse, is there a way to force the use of the this keyword with referring to class members when auto-generating getters and setters?

For example, I want this getter, auto-generated by Eclipse,

public int getId() {
    return id;
}

to be rewritten with

public int getId() {
    return this.id;
}

Is that possibe? If yes, how?

ANSWER:

(The answer is provided by Vitaly, but to make things clear:)

In the top menu, click Window > Preferences.
Then, in the Preferences window, click Java > Code Style
You'll see a checkbox with Qualify all generated field accesses with 'this.' Tick this checkbox.

Works like a charm.

(Notice that 'this.' must be 'this'..)


Solution

  • Open Source -> Generate Getters and Setters

    There is a link at the botton to Code Templates, click it.

    Choose - will you change project settings or workspace settings.

    In Configure generated code and comments, expand Code and select Getter Body, in pattern add this..

    That's it.

    Note: You can open Code Templates from project properties or from workspace preferences.