In Eclipse, after a line like this:
List list = new ArrayList();
Typing "for" just beneath, and followed by "ctrl-space" (by default), will bring several options that can help completing this "for loop":
But if the variable "list" is declared far from here (e.g. as a class field) which may not be directly inferred from this context, or there are many Lists declared,then the assistance doesn't work well:
@@ split line ---
In some cases, Eclipse can assist, but just don't work for member variable. E.g. manually type "another" and ENTER after the ":" didn't persuade Eclipse to guess about it....
(P.S. workable case:
Auto guessed
Entered wanted name, and ENTER, works great
)
Does anyone have any tip to make this assistance work under such scenarios?
What I usually do to solve the content assist with for loop is the following:
create a local variable by typing collection variable that is declared far above and a semicolon:
press Ctrl+2 L
Eclipse generates a new local variable declaration which looks like this:
type my foreach and autocomplete with Ctrl+space getting the following:
place cursor on list2 in the for loop declaration and press Alt+Shift+I which stands for inline variable.
this results in what you want to achieve. The effort is minimal after some practicing:
I have not tried this myself, but take a look at the code template definition. For example, the
foreach
code template is defined in Preferences -> Java -> Editor -> Templates as follows :The definition is as follows :
Notice the variables being used such as
iterable_type
.Now take a look at this Eclipse help page.
There is a variable there called
${id:localVar(type[,type]*)}
which is described as follows :A screenshot of the same :
I believe that if you wanted to increase the scope from which the
foreach
template infers it's variables, you may have to edit the template definition with the appropriate variable.Let me know if this helps. Unfortunately, I have not delved into editing the code templates before so shall not be able to give a concrete example.
I followed Ashutosh Jindal's tip and I managed to configure the template that works (tested with Kepler release). Here it is:
The main point was to change localVar to var in the template definition (the Eclipse docs clearly explain this).
How to use it:
Click for the screenshot
This works almost as good as Intellij templates. The drawbacks are: