preserve comments while converting from lambda to method ref (IDEA-156734)

This commit is contained in:
Anna Kozlova
2016-05-30 20:16:19 +03:00
parent 75da057639
commit 86aa72abe4
3 changed files with 36 additions and 0 deletions

View File

@@ -30,10 +30,12 @@ import com.intellij.psi.util.*;
import com.intellij.refactoring.util.RefactoringChangeUtil;
import com.intellij.util.ArrayUtil;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Collection;
import java.util.Map;
/**
@@ -492,6 +494,10 @@ public class LambdaCanBeMethodReferenceInspection extends BaseJavaBatchLocalInsp
if (functionalInterfaceType == null || !functionalInterfaceType.isValid()) return;
final PsiType denotableFunctionalInterfaceType = RefactoringChangeUtil.getTypeByExpression(lambdaExpression);
if (denotableFunctionalInterfaceType == null) return;
Collection<PsiComment> comments = ContainerUtil.map(PsiTreeUtil.findChildrenOfType(lambdaExpression, PsiComment.class),
(comment) -> (PsiComment)comment.copy());
final String methodRefText = createMethodReferenceText(element, functionalInterfaceType,
lambdaExpression.getParameterList().getParameters());
@@ -508,6 +514,14 @@ public class LambdaCanBeMethodReferenceInspection extends BaseJavaBatchLocalInsp
cast.getOperand().replace(replace);
replace = replace.replace(cast);
}
PsiElement anchor = PsiTreeUtil.getParentOfType(replace, PsiStatement.class);
if (anchor == null) {
anchor = replace;
}
for (PsiComment comment : comments) {
anchor.getParent().addBefore(comment, anchor);
}
JavaCodeStyleManager.getInstance(project).shortenClassReferences(replace);
}
}

View File

@@ -0,0 +1,10 @@
// "Replace lambda with method reference" "true"
class Example {
public void m() {
}
{
//my comments here
Runnable r = this::m
}
}

View File

@@ -0,0 +1,12 @@
// "Replace lambda with method reference" "true"
class Example {
public void m() {
}
{
Runnable r = () -> {
//my comments here
m<caret>();
}
}
}