AbstractCommentRule extends AbstractJavaRule { protected void assignCommentsToDeclarations(ASTCompilationUnit cUnit) { SortedMap<Integer, Node> itemsByLineNumber = orderedCommentsAndDeclarations(cUnit); FormalComment lastComment = null; AbstractJavaNode lastNode = null; for (Entry<Integer, Node> entry : itemsByLineNumber.entrySet()) { Node value = entry.getValue(); if (value instanceof AbstractJavaAccessNode || value instanceof ASTPackageDeclaration) { AbstractJavaNode node = (AbstractJavaNode) value; if (lastComment != null && isCommentNotWithin(lastComment, lastNode, value) && isCommentBefore(lastComment, value)) { node.comment(lastComment); lastComment = null; } if (!(node instanceof AbstractJavaAccessTypeNode)) { lastNode = node; } } else if (value instanceof FormalComment) { lastComment = (FormalComment) value; } } }    }
@Test public void testCommentAssignments() { LanguageVersionHandler handler = LanguageRegistry.getLanguage(JavaLanguageModule.NAME).getVersion("1.8") .getLanguageVersionHandler(); Reader source = new StringReader("public class Foo {" + " \n" + " public void method1() {}\n" + " \n" + " \n" + " \n" + " \n" + " public void method2() {}" + "}"); Node node = handler.getParser(handler.getDefaultParserOptions()).parse("test", source); testSubject.assignCommentsToDeclarations((ASTCompilationUnit) node); List<ASTMethodDeclaration> methods = node.findDescendantsOfType(ASTMethodDeclaration.class); Assert.assertEquals("", methods.get(0).comment().getImage()); Assert.assertEquals("", methods.get(1).comment().getImage()); }