Use JavaParser to refactor a java file

291 Views Asked by At

Could you use the javaparser library to: Rename imported classes, methods and fields? For example:

package org.example;

import org.example.Test;

public class Example {
    public void example() {
        Test t = new Test();
        t.someMethod();
        t.randomField;
   }
}

to

package org.example;

import org.example.Test123;

public class Example {
    public void example() {
        Test123t = new TestTest123);
        t.someOtherMethod();
        t.newName;
   }
}

Edit to add:
Method overload also is taken into consideration, for example:

t.someOverloadedMethod(1, 2, false, null) -> t.name1(1, 2, false, null)
t.someOverloadedMethod() -> t.name2()
1

There are 1 best solutions below

9
On

If JavaParser doesn't build a symbol table defining variable scopes, you can't do this reliably. The problem is that you may attempt to rename a variable X that appears in more than one scope. Your example of method overloading is a special case of this.