private boolean needsImport(Element enclosed, TypeMirror importType) { String importPackagName = getPackageName(importType); TypeElement enclosedElement = findNearestEnclosingType(enclosed); if (importPackagName == null) { return false; } else if (importPackagName.equals("java.lang")) { return false; } else if (importPackagName.equals(getPackageName(topLevelClass)) && ElementUtils.isTopLevelClass(importType)) { return false; // same package name -> no import } String enclosedElementId = ElementUtils.getUniqueIdentifier(enclosedElement.asType()); Set<String> autoImportedTypes = autoImportCache.get(enclosedElementId); if (autoImportedTypes == null) { List<Element> elements = ElementUtils.getElementHierarchy(enclosedElement); autoImportedTypes = new HashSet<>(); for (Element element : elements) { if (element.getKind().isClass()) { collectSuperTypeImports((TypeElement) element, autoImportedTypes); collectInnerTypeImports((TypeElement) element, autoImportedTypes); } } autoImportCache.put(enclosedElementId, autoImportedTypes); } String qualifiedName = getQualifiedName(importType); if (autoImportedTypes.contains(qualifiedName)) { return false; } return true; }
private boolean needsImport(Element enclosed, TypeMirror importType) { String importPackagName = getPackageName(importType); TypeElement enclosedElement = findNearestEnclosingType(enclosed); if (importPackagName == null) { return false; } else if (importPackagName.equals("java.lang")) { return false; } else if (importPackagName.equals(getPackageName(topLevelClass)) && ElementUtils.isTopLevelClass(importType)) { return false; // same package name -> no import } String enclosedElementId = ElementUtils.getUniqueIdentifier(enclosedElement.asType()); Set<String> autoImportedTypes = autoImportCache.get(enclosedElementId); if (autoImportedTypes == null) { List<Element> elements = ElementUtils.getElementHierarchy(enclosedElement); autoImportedTypes = new HashSet<>(); for (Element element : elements) { if (element.getKind().isClass()) { collectSuperTypeImports((TypeElement) element, autoImportedTypes); collectInnerTypeImports((TypeElement) element, autoImportedTypes); } } autoImportCache.put(enclosedElementId, autoImportedTypes); } String qualifiedName = getQualifiedName(importType); if (autoImportedTypes.contains(qualifiedName)) { return false; } return true; }