Search code examples
javaeclipse-jdt

Replacing ArrayAccess with MethodInvocation in JDT


I need to transform

xyz[3].aaa[1].bbb[2].jjj

to

getXyz(3).getAaa(1).getBbb(2).getJjj()

using JDT core.

Replace ArrayAccess with some getter Method does not help because the array access visited are as follows:-

xyz[3].aaa[1].bbb[2]
xyz[3].aaa[1]
xyz[3]

So replacing just the ArrayAccess to getter will loose some replacements.

Another option I tried is to visit FieldAccess but doing that I am left with something like

getXyz(3).getAaa(1)[1].getBbb(2)[2].getJjj()

Is there a way to replace the [1] or [2] or rather is there was to parse and get hold of just the aaa[1], bbb[2] to remove or replace ?


Solution

  • Found answer to my own question. Short answer is that in the expression xyz[3].aaa[1] the xyz[3].aaa needs to be treated as an array with index expression as 1 so that the aaa[1] or the [1] gets accounted for properly.

    However programatically I found following approach much easier to deal with. The approach is to treat the array expression in here as method invocation by simple replacement replace("\"", "").replace("+", "").replace('[', '(').replace(']', ')') the problem reduces to renaming the methods.

    @Test
    public void testArray() throws Exception {
        String testExpr = "xyz[3].aaa[1].bbb[2]";
    
        Document document;
        ASTParser parser;
        parser = ASTParser.newParser(AST.JLS8);
        parser.setKind(ASTParser.K_EXPRESSION);
        parser.setResolveBindings(true);
        String exprString = testExpr.replace("\"", "").replace("+", "").replace('[', '(').replace(']', ')');
    
        document = new Document(exprString);
        parser.setSource(document.get().toCharArray());
        Object o = parser.createAST(null);
    
        if (o instanceof CompilationUnit) {
            CompilationUnit cu = (CompilationUnit) o;
            IProblem[] problems = cu.getProblems();
            System.err.println(problems);
        }
        Expression expr = (Expression) o;
        final ASTRewrite rewriter = ASTRewrite.create(expr.getAST());
        final AST ast = expr.getAST();
        final TextEditGroup textEdits = new TextEditGroup("test");
    
        expr.accept(new ASTVisitor() {
            @Override
            public boolean visit(MethodInvocation node) {
                String getter = getGetter(node.getName().getIdentifier().toString());
    
                rewriter.replace(node.getName(), 
                        ast.newSimpleName(getter),
                        textEdits);
                return super.visit(node);
            }
    
    
        });
    
        TextEdit edits = rewriter.rewriteAST(document, null);
        edits.apply(document);
    
        assertEquals("getXyz(3).getAaa(1).getBbb(2)", 
                document.get());
    }