1 | package javaparser;
|
---|
2 |
|
---|
3 | import static org.junit.Assert.assertTrue;
|
---|
4 |
|
---|
5 | import java.util.Arrays;
|
---|
6 |
|
---|
7 | import org.eclipse.jdt.annotation.NonNull;
|
---|
8 | import org.junit.Test;
|
---|
9 |
|
---|
10 | import com.github.javaparser.JavaParser;
|
---|
11 | import com.github.javaparser.ParserConfiguration;
|
---|
12 | import com.github.javaparser.ast.CompilationUnit;
|
---|
13 | import com.github.javaparser.ast.Node;
|
---|
14 | import com.github.javaparser.ast.nodeTypes.NodeWithAnnotations;
|
---|
15 | import com.github.javaparser.symbolsolver.JavaSymbolSolver;
|
---|
16 | import com.github.javaparser.symbolsolver.resolution.typesolvers.CombinedTypeSolver;
|
---|
17 | import com.github.javaparser.symbolsolver.resolution.typesolvers.ReflectionTypeSolver;
|
---|
18 |
|
---|
19 | /**
|
---|
20 | * #285 the annotation disappears from foreach variable...
|
---|
21 | *
|
---|
22 | */
|
---|
23 | public class AnnotatedForEachVar {
|
---|
24 |
|
---|
25 | public static void main(String[] args) {
|
---|
26 | for (final @NonNull String s : Arrays.asList("a", "b")) {
|
---|
27 | System.out.println(s);
|
---|
28 | }
|
---|
29 | }
|
---|
30 |
|
---|
31 | String CODE = "import org.eclipse.jdt.annotation.NonNull;\n"
|
---|
32 | + "public class AnnotatedForEachVar {\n" + "\n"
|
---|
33 | + " public static void main(String[] args) {\n"
|
---|
34 | + " for (final @NonNull String s : Arrays.asList(\"a\", \"b\")) {\n"
|
---|
35 | + " System.out.println(s);\n" + " }\n" + " }\n"
|
---|
36 | + "}\n";
|
---|
37 |
|
---|
38 | @Test
|
---|
39 | public void testResolve() {
|
---|
40 | ParserConfiguration conf = new ParserConfiguration();
|
---|
41 | CombinedTypeSolver typeSolver = new CombinedTypeSolver();
|
---|
42 | typeSolver.add(new ReflectionTypeSolver(false));
|
---|
43 | JavaSymbolSolver symbolSolver = new JavaSymbolSolver(typeSolver);
|
---|
44 | conf.setSymbolResolver(symbolSolver);
|
---|
45 | JavaParser parser = new JavaParser(conf);
|
---|
46 |
|
---|
47 | CompilationUnit res = parser.parse(CODE).getResult().get();
|
---|
48 | System.out.println(res);
|
---|
49 |
|
---|
50 | assertTrue(containsAnnotation(res));
|
---|
51 | }
|
---|
52 |
|
---|
53 | /**
|
---|
54 | *
|
---|
55 | * @param node a node in the parse tree
|
---|
56 | * @return true if node or any of its children contains an annotation
|
---|
57 | */
|
---|
58 | private boolean containsAnnotation(Node node) {
|
---|
59 | if (node instanceof NodeWithAnnotations
|
---|
60 | && ((NodeWithAnnotations) node).getAnnotations().isNonEmpty())
|
---|
61 | return true;
|
---|
62 |
|
---|
63 | for (Node child : node.getChildNodes())
|
---|
64 | if (containsAnnotation(child))
|
---|
65 | return true;
|
---|
66 | return false;
|
---|
67 | }
|
---|
68 |
|
---|
69 | }
|
---|