2

i am using java parser to read a java file. then i have problem with how to access variable in each method, then modifying the variable name and type in each method.

public static void main(String[] args) throws Exception {
    // creates an input stream for the file to be parsed
    FileInputStream in = new FileInputStream("test.java");

    CompilationUnit cu;
    try {
        // parse the file
        cu = JavaParser.parse(in);
    } finally {
        in.close();
    }

    // change the methods names and parameters
    changeMethods(cu);

    // prints the changed compilation unit
    System.out.println(cu.toString());
}

private static void changeMethods(CompilationUnit cu) {
    List<TypeDeclaration> types = cu.getTypes();
    for (TypeDeclaration type : types) {
        List<BodyDeclaration> members = type.getMembers();
        for (BodyDeclaration member : members) {
            if (member instanceof MethodDeclaration) {
                // what must i do?
            }
        }
    }
}

[UPDATE]

For more details, i have a method such as below:

 private double[] getExtremeValues(double[] d) {    
    double min = Double.MAX_VALUE;  
    double max = -min;

}

in that method, i just want to modify 'double max' with 'double max1'. The second question, how to get 'double[] d' in the method parameter? Please help! Thanks

Samsul Arifin
  • 247
  • 1
  • 6
  • 24

2 Answers2

0

Do you want to modify all variables contained in a method? In that case you will either need to use recursion or use a visitor (see for example the GenericVisitorAdapter).

If instead you want to change just the parameters look at the method "getParameters" in MethodDeclaration.

In both cases note that changing just the name of the variable will probably break the code: you need to change also all references to that variable.

What do you mean by changing the type of a method? That can be easily done with the method setType of MethodDeclaration.

Federico Tomassetti
  • 2,100
  • 1
  • 19
  • 26
0

Here is one example which modifies the method name. You need to override some methods

    private static class MethodNameModifier extends ModifierVisitor<Void> {
        @Override
        public MethodDeclaration visit(MethodDeclaration md, Void arg) {
            super.visit(md, arg);
            //System.out.println(md.getName());
            md.setName("x");
            return md;
        }
    }
Frank Xu
  • 63
  • 3