PsiExpression (@NotNull PsiReferenceExpression ref, @NotNull PsiMember member) { PsiMember containingMember = PsiTreeUtil.getParentOfType(ref, PsiMethod.class, PsiClassInitializer.class, PsiField.class); if (!member.hasModifierProperty(PsiModifier.STATIC) && isStaticMember(containingMember)) { return null; } PsiElementFactory factory = JavaPsiFacade.getElementFactory(ref.getProject()); PsiClass memberClass = member.getContainingClass(); if (memberClass != null) { if (member.hasModifierProperty(PsiModifier.STATIC)) { if (memberClass.getName() == null) return null; return factory.createReferenceExpression(memberClass); } PsiClass containingClass = ClassUtils.getContainingClass(ref); if (containingClass == null) { containingClass = PsiTreeUtil.getContextOfType(ref, PsiClass.class); } if (!InheritanceUtil.isInheritorOrSelf(containingClass, memberClass, true)) { if (!member.hasModifierProperty(PsiModifier.STATIC) && isStaticMember(containingClass)) return null; containingClass = ClassUtils.getContainingClass(containingClass); while (containingClass != null && !InheritanceUtil.isInheritorOrSelf(containingClass, memberClass, true)) { if (!member.hasModifierProperty(PsiModifier.STATIC) && isStaticMember(containingClass)) return null; containingClass = ClassUtils.getContainingClass(containingClass); } if (containingClass != null) { String thisQualifier = containingClass.getQualifiedName(); if (thisQualifier == null) { if (PsiUtil.isLocalClass(containingClass)) { thisQualifier = containingClass.getName(); } else { // Cannot qualify anonymous class return null; } } return factory.createExpressionFromText(thisQualifier + "." + PsiKeyword.THIS, ref); } } } return factory.createExpressionFromText(PsiKeyword.THIS, ref); }