final in "foreach" loop

This commit is contained in:
Andrey Starovoyt
2014-05-23 17:49:50 +04:00
parent 0c86e1ed87
commit 438a3e28ae
4 changed files with 36 additions and 5 deletions
@@ -24,6 +24,7 @@ import com.intellij.codeInsight.template.macro.IterableComponentTypeMacro;
import com.intellij.codeInsight.template.macro.SuggestVariableNameMacro;
import com.intellij.openapi.editor.Editor;
import com.intellij.psi.PsiElement;
import com.intellij.psi.codeStyle.JavaCodeStyleSettingsFacade;
import static com.intellij.codeInsight.template.postfix.util.JavaPostfixTemplatesUtils.IS_ITERABLE_OR_ARRAY;
import static com.intellij.codeInsight.template.postfix.util.JavaPostfixTemplatesUtils.JAVA_PSI_INFO;
@@ -35,7 +36,9 @@ public class ForeachPostfixTemplate extends StringBasedPostfixTemplate {
@Override
public void expandWithTemplateManager(TemplateManager manager, PsiElement expression, Editor editor) {
Template template = manager.createTemplate("", "", "for ($type$ $name$ : $variable$) {\n $END$\n}");
String finalPart = JavaCodeStyleSettingsFacade.getInstance(expression.getProject()).isGenerateFinalLocals() ? "final " : "";
Template template = manager.createTemplate("", "", "for (" + finalPart + "$type$ $name$ : $variable$) {\n $END$\n}");
MacroCallNode type = new MacroCallNode(new IterableComponentTypeMacro());
MacroCallNode name = new MacroCallNode(new SuggestVariableNameMacro());
String variable = "variable";
@@ -0,0 +1,6 @@
public class Foo {
void m() {
Object[] xs = new Object[]{1, 2, 3};
xs.for<caret>
}
}
@@ -0,0 +1,8 @@
public class Foo {
void m() {
Object[] xs = new Object[]{1, 2, 3};
for (final Object x : xs) {
<caret>
}
}
}
@@ -15,9 +15,17 @@
*/
package com.intellij.codeInsight.template.postfix.templates;
import com.intellij.psi.codeStyle.CodeStyleSettings;
import com.intellij.psi.codeStyle.CodeStyleSettingsManager;
import org.jetbrains.annotations.NotNull;
public class ForeachTemplateTest extends PostfixTemplateTestCase {
@NotNull
@Override
protected String getSuffix() {
return "for";
}
public void testInts() {
doTest();
}
@@ -26,9 +34,15 @@ public class ForeachTemplateTest extends PostfixTemplateTestCase {
doTest();
}
@NotNull
@Override
protected String getSuffix() {
return "for";
public void testFinalLocals() {
CodeStyleSettings settings = CodeStyleSettingsManager.getSettings(getProject());
boolean oldGenerateFinalLocals = settings.GENERATE_FINAL_LOCALS;
try {
settings.GENERATE_FINAL_LOCALS = true;
doTest();
}
finally {
settings.GENERATE_FINAL_LOCALS = oldGenerateFinalLocals;
}
}
}