PsiComment (PsiMethod method, String javadoc, boolean replace) { final Project project = method.getProject(); PsiElementFactory factory = JavaPsiFacade.getElementFactory(project); PsiComment comment = factory.createCommentFromText(javadoc, null); // does a method already exists? PsiDocComment doc = method.getDocComment(); if (doc != null) { if (replace) { // javadoc already exists, so replace doc.replace(comment); final CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(project); codeStyleManager.reformat(method); // to reformat javadoc return comment; } else { // do not replace existing javadoc return null; } } else { // add new javadoc method.addBefore(comment, method.getFirstChild()); final CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(project); codeStyleManager.reformat(method); // to reformat javadoc return comment; } }