26

Is there a way in IntelliJ Idea to force this. to be automatically placed into code on a format or save or at the very least show an error if it should be in there?

Dan King
  • 1,080
  • 1
  • 11
  • 28

4 Answers4

31

You can turn on the following inspections:

  • File > Settings > [Project Settings] > Inspections > Code Style Issues >
    • "Instance method call not qualified with 'this'"
    • "Instance fields access not qualified with 'this'"

That will highlight any missing 'this.' declarations. With your cursor on the highlight, Alt+Enter will bring up the quick fix to add 'this". If on that initial pop-up you arrow to the right, You can select the "Fix All "Instance Method call not qualified with 'this'" problems" option to fix all issues in the current file. (you'll need to do this for both methods and fields)

If you run the inspection on the project - either by the Analyze > Inspect Code... or by the Analyze > Run Inspection by Name... option you can then apply the fix to all files in the project (or module or package, etc.)

There is no way to get the quick fix to occur on a reformat.

Javaru
  • 30,412
  • 11
  • 93
  • 70
4

You can add the 'this.' qualifier to fields by using the 'Save Actions' Plugin (which I also recommend to use for other reasons). Just install it via Settings > Plugins > Browse repositories and be sure to check the quick fix 'Qualify field access with this' later.

2

In new versions of IntelliJ when committing code or selecting a warning you can choose the option Cleanup, which will add this. to the member variables in your code.

Dan King
  • 1,080
  • 1
  • 11
  • 28
  • Can you describe precisely where this feature is located? I cannot find it in IntelliJ 2018.1. – Basil Bourque May 10 '18 at 23:16
  • On a commit you can check the cleanup button on the Commit dialog or depending on the inspection you might have a cleanup which will apply a number of things to the class. Adding "this." being one of them – Dan King May 11 '18 at 16:48
2

There is a code inspection option available for this (File > Settings > Editor > Inspections):

enter image description here

You can turn this inspection on to get warnings.

The code cleanup option can be used from menu (Analyze > Code Cleanup...)

Saikat
  • 14,222
  • 20
  • 104
  • 125