在方法Java JDT解析器中检测相同的变量

时间:2015-12-16 15:50:51

标签: java eclipse-plugin abstract-syntax-tree eclipse-jdt

我一直在用JDT实现一个Java解析器,我在同一方法中检测相同的变量声明时遇到了问题。例如,我有如下课程:

public double method(double[] data) {
    int _ii = 0;
    int _ii = 0; //same variable name, data type and value

    for (int _ii = 0; _ii < _dimensi; _ii++) {
        _temp += data[_ii];
    }
    _output = _temp / _dimensi;

    return _output;
}

上面的类有两个具有相同名称的变量(int _ii = 0),那么我的目标是在同一个方法中找到重复变量并删除其中一个。所以代码将是:

public double method(double[] data) {
    int_ii = 0;

    for (int _ii = 0; _ii < _dimensi; _ii++) {
        _temp += data[_ii];
    }
    _output = _temp / _dimensi;

    return _output;
}

到目前为止我的代码:

  public static void main(String args[]){

     String str = "public class Classname{"
            + "public double method(double[] data) {\n" +
            "    int _ii = 0;\n" +
            "    int _ii = 0; //same variable name, data type and value\n" +
            "\n" +
            "    for (int _ii = 0; _ii < _dimensi; _ii++) {\n" +
            "        _temp += data[_ii];\n" +
            "    }\n" +
            "    _output = _temp / _dimensi;\n" +
            "\n" +
            "    return _output;\n" +
            "}"
            + "}";

    ASTParser parser = ASTParser.newParser(AST.JLS3);
    parser.setSource(str.toCharArray());

    parser.setKind(ASTParser.K_COMPILATION_UNIT);

    final CompilationUnit cu = (CompilationUnit) parser.createAST(null);

    cu.accept(new ASTVisitor() {
                    public boolean visit(MethodDeclaration method){
                            Block block = method.getBody();

                            block.accept(new ASTVisitor() {

                                    public boolean visit(VariableDeclarationFragment var) {
                                        System.out.println("Variable " + var.getName()+", in Method "+method.getName()+ "' Method line " + cu.getLineNumber(method.getStartPosition()));
                                        Multimap<Integer, String> multimap = ArrayListMultimap.create();

                                        multimap.put(1, var.getName()); // variable name
                                        multimap.put(1, cu.getLineNumber(method.getStartPosition())); // method line
                                        multimap.put(1, method.getName()); // method name

                                        //Then what should i do if found variable name, method line and method name more than one in the Multimap?

                                        return false;
                                    }
                            });


                      return false;
                    }

    });
}

任何人都请帮助我,谢谢:)

0 个答案:

没有答案