introduce variable: prefer expr type to expected when possible(IDEA-175248)

This commit is contained in:
Anna.Kozlova
2017-07-03 16:53:16 +02:00
parent b6be652742
commit 596b751e24
4 changed files with 42 additions and 1 deletions
@@ -357,7 +357,8 @@ public class RefactoringUtil {
public static PsiType getTypeByExpressionWithExpectedType(PsiExpression expr) {
PsiElementFactory factory = JavaPsiFacade.getInstance(expr.getProject()).getElementFactory();
PsiType type = getTypeByExpression(expr, factory);
PsiType typeByExpression = getTypeByExpression(expr, factory);
PsiType type = typeByExpression;
final boolean isFunctionalType = LambdaUtil.notInferredType(type);
final boolean isDenotable = PsiTypesUtil.isDenotableType(expr.getType());
if (type != null && !isFunctionalType && isDenotable) {
@@ -365,6 +366,9 @@ public class RefactoringUtil {
}
ExpectedTypeInfo[] expectedTypes = ExpectedTypesProvider.getExpectedTypes(expr, false);
if (expectedTypes.length == 1 || (isFunctionalType || !isDenotable)&& expectedTypes.length > 0 ) {
if (typeByExpression != null && Arrays.stream(expectedTypes).anyMatch(typeInfo -> typeInfo.getType().equals(typeByExpression))) {
return type;
}
type = expectedTypes[0].getType();
if (!type.equalsToText(CommonClassNames.JAVA_LANG_OBJECT)) return type;
}
@@ -0,0 +1,17 @@
import java.util.List;
class CloseAction {
public void performAction() throws IOException {
}
}
class Foo {
void performAction() {
}
void bar(List<? extends Foo> f) {
Foo m = f.get(0);
m.performAction();
}
}
@@ -0,0 +1,16 @@
import java.util.List;
class CloseAction {
public void performAction() throws IOException {
}
}
class Foo {
void performAction() {
}
void bar(List<? extends Foo> f) {
<selection>f.get(0)</selection>.performAction();
}
}
@@ -567,6 +567,10 @@ public class IntroduceVariableTest extends LightCodeInsightTestCase {
doTest(new MockIntroduceVariableHandler("m", false, false, false, "IA"));
}
public void testChooseTypeExpressionWhenNotDenotable() throws Exception {
doTest(new MockIntroduceVariableHandler("m", false, false, false, "Foo"));
}
private void doTest(IntroduceVariableBase testMe) {
String baseName = "/refactoring/introduceVariable/" + getTestName(false);
configureByFile(baseName + ".java");