Eclipse JDT ASTParser convert enum declaration node incorrectly

爷,独闯天下 提交于 2020-01-13 03:47:18

问题


I am working on analyzing Java code by using JDT and going to build a standalone analysis tool depend on org.eclipse.jdt.core package instead of an eclipse plug-in. But I found that my tool did not work correctly on enum declaration node which appeared in Java code. In my AST which created by jdt, keyword enum was regarded as a typename instead of an enum declaration. So I want to know how I should be can ensure that my tool can deal the enum declaration correctly.

The jdt package that I used is "org.eclipse.jdt.core_3.8.3.v20130121-145325.jar". The createAST code is:

char[] javaprogram=getJavaFile(javaFileName);
ASTParser parser = ASTParser.newParser(AST.JLS4);
parser.setSource(javaprogram);
parser.setKind(ASTParser.K_COMPILATION_UNIT);
final CompilationUnit cu = (CompilationUnit) parser.createAST(null);

the java input is like below:

package test;

enum Color
{
  RED(255, 0, 0),  BLUE(0, 0, 255),  BLACK(0, 0, 0),    YELLOW(255, 255, 0),  GREEN(0, 255, 0);

  private int redValue;
  private int greenValue;
  private int blueValue;

  private Color(int rv, int gv, int bv)
  {
    this.redValue = rv;
    this.greenValue = gv;
    this.blueValue = bv;
  }

  public String toString()
  {
    return super.toString() + "(" + this.redValue + "," + this.greenValue + "," + this.blueValue + ")";
  }
}

But using astparser.createAST() to get CompilationUnit node just got the code which is just contained the package code:

package test;

The problem is solved by adding the CompilerOptions which code is shown below:

Map options = JavaCore.getOptions();
options.put(JavaCore.COMPILER_COMPLIANCE, JavaCore.VERSION_1_5);
options.put(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, JavaCore.VERSION_1_5);
options.put(JavaCore.COMPILER_SOURCE, JavaCore.VERSION_1_5);
parser.setCompilerOptions(options);

回答1:


As you answered yourself you have to set compiler version to a newer one because the default one is 1.3

Map options = JavaCore.getOptions();
System.out.println(options.get(JavaCore.COMPILER_SOURCE)); //outputs 1.3

However (I think) enum declaration was added only in 1.5 so you have to set it to 1.5 or above. Also I believe it's enough to set only COMPILER_SOURCE

Map options = JavaCore.getOptions();
options.put(JavaCore.COMPILER_SOURCE, JavaCore.VERSION_1_5); //or newer version
parser.setCompilerOptions(options);


来源:https://stackoverflow.com/questions/21924881/eclipse-jdt-astparser-convert-enum-declaration-node-incorrectly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!