[java-inspections] IDEA-357190 Support JEP477 - Remove unnecessary qualification is not suggested when it can be

- check if class is already imported

GitOrigin-RevId: 11a43bf80302194a4f8b34125de2bb741f1f3bac
This commit is contained in:
Mikhail Pyltsin
2024-08-08 18:26:48 +02:00
committed by intellij-monorepo-bot
parent d3c5f5a6c0
commit 0f5aa949cb
5 changed files with 59 additions and 20 deletions

View File

@@ -130,7 +130,8 @@ public final class ImportUtils {
if (hasExactImportConflict(fqName, file)) {
return false;
}
if (hasOnDemandImportConflict(fqName, file, true)) {
if (hasOnDemandImportConflict(fqName, file, true) && !isAlreadyImported(file, fqName)
) {
return false;
}
if (containsConflictingReference(file, fqName)) {
@@ -142,6 +143,34 @@ public final class ImportUtils {
return !containsConflictingTypeParameter(fqName, context);
}
/**
* Checks if the class with the given fully qualified name is already imported in the specified Java file.
*
* @param file the Java file to check for the import.
* @param fullyQualifiedName the fully qualified name of the class to check.
* @return true if the class is already imported, false otherwise.
*/
public static boolean isAlreadyImported(@NotNull PsiJavaFile file, @NotNull String fullyQualifiedName) {
String className = extractClassName(file, fullyQualifiedName);
Project project = file.getProject();
PsiResolveHelper resolveHelper = PsiResolveHelper.getInstance(project);
PsiClass psiClass = resolveHelper.resolveReferencedClass(className, file);
return psiClass != null && fullyQualifiedName.equals(psiClass.getQualifiedName());
}
private static @NotNull String extractClassName(@NotNull PsiJavaFile file, @NotNull String fullyQualifiedName) {
for (PsiClass aClass : file.getClasses()) {
String outerClassName = aClass.getQualifiedName();
if (outerClassName != null && fullyQualifiedName.startsWith(outerClassName)) {
return fullyQualifiedName.substring(outerClassName.lastIndexOf('.') + 1);
}
}
return ClassUtil.extractClassName(fullyQualifiedName);
}
private static boolean containsConflictingTypeParameter(String fqName, PsiElement context) {
final String shortName = ClassUtil.extractClassName(fqName);
PsiElement parent = context.getParent();