public static GrReferenceExpression qualifyReference(GrReferenceExpression referenceExpression,
                                                        final PsiMember member,
                                                        @Nullable final PsiClass qualifyingClass) throws IncorrectOperationException {
    PsiManager manager = referenceExpression.getManager();
    GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(manager.getProject());

    GrReferenceExpression expressionFromText;
    if (qualifyingClass == null) {
      final PsiClass parentClass = PsiTreeUtil.getParentOfType(referenceExpression, PsiClass.class);
      final PsiClass containingClass = member.getContainingClass();
      if (parentClass != null && !InheritanceUtil.isInheritorOrSelf(parentClass, containingClass, true)) {
        expressionFromText = (GrReferenceExpression)factory.createExpressionFromText(containingClass.getQualifiedName()+ ".this." + member.getName());
      }
      else {
        expressionFromText = (GrReferenceExpression)factory.createExpressionFromText("this." + member.getName());
      }
    }
    else {
      expressionFromText = (GrReferenceExpression)factory.createExpressionFromText(qualifyingClass.getQualifiedName()+ '.' + member.getName());
    }
    CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(manager.getProject());
    expressionFromText = (GrReferenceExpression)codeStyleManager.reformat(expressionFromText);
    return (GrReferenceExpression)referenceExpression.replace(expressionFromText);
  }
public static GrReferenceExpression qualifyReference(GrReferenceExpression referenceExpression,
                                                        final PsiMember member,
                                                        @Nullable final PsiClass qualifyingClass)