Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prefix existing fields with m

I'm trying to do a structural replacement for my project. I have a package with 100+ classes, each with 1-20 fields. Our project is migrating to Hungarian notation, which means all private fields have to be prefixed with m.

I know IntelliJ can add prefixes for new fields, but I don't know the recipe for doing a batch Refactor->Rename for all fields.

Regex doesn't work because said fields are used through the application in all kind of contexts, method calls, assignations, arithmetical ops...

What would be the best approach that's not manual?

like image 730
MLProgrammer-CiM Avatar asked Mar 30 '16 12:03

MLProgrammer-CiM


1 Answers

Based on answers to similar questions (here, here and here) I guess you can use javaparser and create a small utility to do the refactor for you.

Here is something to get you started:

import japa.parser.JavaParser;
import japa.parser.ParseException;
import japa.parser.ast.CompilationUnit;
import japa.parser.ast.body.FieldDeclaration;
import japa.parser.ast.body.VariableDeclaratorId;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class HungarianNotationRefactor {

    public static void main(String[] args) throws IOException, ParseException {
        File file = new File(args[0]);

        CompilationUnit cu;
        cu = JavaParser.parse(file);

        // get all types in file
        cu.getTypes()
                .stream()

                // get all members
                .flatMap(type -> type.getMembers().stream())

                // filter only fields
                .filter(member -> member instanceof FieldDeclaration)
                .map(member -> (FieldDeclaration) member)

                // get all variables and rename
                .flatMap(field -> field.getVariables().stream())
                .forEach(var -> var.setId(new VariableDeclaratorId("m_" + var.getId())));

        try (FileWriter out = new FileWriter(file)) {
            out.append(cu.toString());
        }
        System.out.println(cu.toString());
    }
}

This will rename fields but not this.field occurrences (but it's a start).

like image 175
Yoav Aharoni Avatar answered Oct 22 '22 18:10

Yoav Aharoni