SyntaxTreeNameFinder extends BaseTreeVisitor { public static String getName(Tree syntaxNode) { SyntaxTreeNameFinder finder = new SyntaxTreeNameFinder(); syntaxNode.accept(finder); return finder.getName(); }  static String getName(Tree syntaxNode); @Override void visitIdentifier(IdentifierTree tree); @Override void visitMemberSelectExpression(MemberSelectExpressionTree tree); @Override void visitSwitchStatement(SwitchStatementTree tree); @Override void visitParenthesized(ParenthesizedTree tree); @Override void visitTypeCast(TypeCastTree tree); @Override void visitMethodInvocation(MethodInvocationTree tree); @Override void visitVariable(VariableTree tree);  }
@Test void testClassCast() { MethodTree tree = buildSyntaxTree("public boolean equals(Object obj) {((String) obj).length();}"); BlockTree block = tree.block(); StatementTree statementTree = block.body().get(0); MethodInvocationTree mit = (MethodInvocationTree) ((ExpressionStatementTree) statementTree).expression(); MemberSelectExpressionTree mse = (MemberSelectExpressionTree) mit.methodSelect(); assertThat(SyntaxTreeNameFinder.getName(mse)).isEqualTo("obj"); }
@Test void testCatchParameter() { MethodTree tree = buildSyntaxTree("public void test() {try {} catch (Exception ex) {} }"); assertThat(SyntaxTreeNameFinder.getName(tree)).isEqualTo("ex"); }
@Test void testVariableWithInitializer() { MethodTree tree = buildSyntaxTree("public void test() {int i = length;}"); assertThat(SyntaxTreeNameFinder.getName(tree)).isEqualTo("length"); }
@Test void testFieldAccess() { MethodTree tree = buildSyntaxTree("public void test() {this.field = value;} Object field;"); BlockTree block = tree.block(); AssignmentExpressionTree assignmentTree = (AssignmentExpressionTree) ((ExpressionStatementTree) block.body().get(0)).expression(); assertThat(SyntaxTreeNameFinder.getName(assignmentTree.variable())).isEqualTo("field"); tree = buildSyntaxTree("public void test() {super.field = value;}"); block = tree.block(); assignmentTree = (AssignmentExpressionTree) ((ExpressionStatementTree) block.body().get(0)).expression(); assertThat(SyntaxTreeNameFinder.getName(assignmentTree.variable())).isEqualTo("field"); tree = buildSyntaxTree("public void test() {A.field = value;}"); block = tree.block(); assignmentTree = (AssignmentExpressionTree) ((ExpressionStatementTree) block.body().get(0)).expression(); assertThat(SyntaxTreeNameFinder.getName(assignmentTree.variable())).isEqualTo("A"); tree = buildSyntaxTree("public void test() {foo().field = value;}"); block = tree.block(); assignmentTree = (AssignmentExpressionTree) ((ExpressionStatementTree) block.body().get(0)).expression(); assertThat(SyntaxTreeNameFinder.getName(assignmentTree.variable())).isEqualTo("foo"); }