Java – prefix existing fields with M
•
Java
I'm trying to make a structural replacement for my project I have a package of 100 classes, each containing 1 - 20 fields Our project is migrating to Hungarian notation, which means that all private fields must be prefixed with M
I know IntelliJ can prefix new fields, but I don't know the recipe for batch refactoring for all fields – > renaming
Regular expressions don't work because all fields are used by applications in all types of contexts, method calls, assignments, arithmetic operations
What is the best method not manual?
Solution
Based on the answers to similar questions (here, here and
Here's what gets 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 the field, but will not rename it Field event (but it's a start)
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码