Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange result of eclipse AST with inner enum class

I am experimenting with eclipse jdt AST and am running into a strange behaviour that I can find no explanation for.

Here is my example code:

public static void main(String[] args) {
    StringBuilder content = new StringBuilder();
    content.append("class Foo {");
    content.append("    enum Bar {");
    content.append("        VALUE;");
    content.append("        int getValue() {");
    content.append("            return 4;");
    content.append("        }");
    content.append("    }");
    content.append("    int getValue() {");
    content.append("        return 42;");
    content.append("    }");
    content.append("}");

    ASTParser parser = ASTParser.newParser(AST.JLS13);
    parser.setKind(ASTParser.K_COMPILATION_UNIT);
    parser.setSource(content.toString().toCharArray());

    CompilationUnit astNode = (CompilationUnit) parser.createAST(null);

    Visitor rtVisitor = new Visitor();
    astNode.accept(rtVisitor);

}

private static class Visitor extends ASTVisitor {

    @Override
    public boolean visit(TypeDeclaration node) {
        System.out.println(node);
        return super.visit(node);
    }
}

As you can see, I am defining a very simple example class that has an inner enum class where both classes have a method with the same signature.

Strangely though the output of this code (i.e. the parsed TypeDeclaration) is

class Foo {
  enum Bar;
{
  }
  int getValue(){
    return 4;
  }
{
  }
  int getValue(){
    return 42;
  }
}

For some reason, the body of the TypeDeclaration consists of:

  1. a FieldDeclaration: enum Bar;
  2. an Initializer: {}
  3. a MethodDeclaration: int getValue(){ return 4; }
  4. another Initializer: {}
  5. another MethodDeclaration: int getValue(){ return 42; }

This leads to my actual code throwing an error because it looks like there are two methods with identical signature.

Why am I not getting the enum as an actual EnumDeclaration with inner methods but rather it looks like the method inside the enum is actually declared in the outer class itself?

I do not think that this is a bug because the AST View in eclipse handles a similar class perfectly fine, but I cannot figure out what I am doing wrong. Enabling binding resolution did not help.

like image 966
sina Avatar asked Oct 27 '22 17:10

sina


1 Answers

You need to set compiler options by calling parser.setCompilerOptions, so that the source file is processed correctly.
Since you are using the enum keyword, you need at least Java 5 compliance:

ASTParser parser = ASTParser.newParser(AST.JLS13);
Map options = JavaCore.getOptions();
JavaCore.setComplianceOptions(JavaCore.VERSION_1_5, options);
parser.setCompilerOptions(options);
parser.setKind(ASTParser.K_COMPILATION_UNIT);
parser.setSource(content.toString().toCharArray());
like image 199
mcernak Avatar answered Nov 09 '22 11:11

mcernak