大规模Java代码文件修改 - 删除方法,注释等

时间:2014-01-09 18:10:03

标签: java refactoring

我从一个非常古老的项目中获得了一堆代码,他们生成了许多冗余方法和注释。

无论如何快速,从这个包中的所有类中删除-method“doOldThing()” - 删除所有类中的所有@AnnotationObsoluted?

我知道我们可以使用搜索和替换,但编写正则表达式来删除这些需要很长时间。我想我们可以解析一个Java文件,然后删除“doOldThings()”方法,检查@AnnotationObsoluted然后删除。任何的想法? TKS。

2 个答案:

答案 0 :(得分:1)

如果有人感兴趣,这里是我写的用于清理方法(按名称)和import语句的小型util的代码。

    import com.googlecode.java2objc.main.Config;
    import com.googlecode.java2objc.main.Main;
    import japa.parser.ASTHelper;
    import japa.parser.JavaParser;
    import japa.parser.ParseException;
    import japa.parser.ast.CompilationUnit;
    import japa.parser.ast.ImportDeclaration;
    import japa.parser.ast.body.*;
    import japa.parser.ast.expr.AnnotationExpr;
    import japa.parser.ast.type.ClassOrInterfaceType;

    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.List;

    /**
     * User: lent
     * Date: 10/01/2014
     */
    public class CleanUpAndModelRegeneration
    {
        public static void main(String... args) throws IOException, ParseException
        {
            List<File> results =
                    listFilesForFolder(new File("\\LocationOfYourCode"), new ArrayList<File>());

            List<String> javaFiles = new ArrayList<String>();
            for (File codeFile : results)
            {
                // creates an input stream for the file to be parsed
                FileInputStream in = new FileInputStream(codeFile);

                CompilationUnit cu = null;
                try
                {
                    // parse the file
                    cu = JavaParser.parse(in);
                    removeMethod(cu, "toString");
                    removeMethod(cu, "append");
                    removeMethod(cu, "appendFields");
                    removeMethod(cu, "fromValue");
                    optimizeImport(cu);
                    cleanUpInterfaces("ToString", cu.getTypes());
                    cleanUpAnnotationForEnum(cu);

                    // prints the resulting compilation unit to default system output
                    System.out.println(cu.toString());


                }
                catch (Exception e)
                {
                    System.out.println(e.getMessage());
                }
                finally
                {
                    in.close();
                }

                FileOutputStream fileOutputStream = new FileOutputStream(codeFile, false);
                fileOutputStream.write(cu.toString().getBytes());
                fileOutputStream.flush();

                javaFiles.add(codeFile.toString());
            }

            try
            {
                Config config = new Config();
                Main main = new Main(config, javaFiles);
                main.execute();
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }

        private static void cleanUpAnnotationForEnum(CompilationUnit cu)
        {
            for (TypeDeclaration type : cu.getTypes())
            {
                if (type instanceof EnumDeclaration)
                {
                    EnumDeclaration enumDeclaration = (EnumDeclaration) type;
                    if (enumDeclaration.getAnnotations() != null)
                    {
                        enumDeclaration.getAnnotations().clear();
                    }

                    for (BodyDeclaration member : enumDeclaration.getMembers())
                    {
                        List<AnnotationExpr> annotations = member.getAnnotations();
                        if (annotations != null)
                        {
                            annotations.clear();
                        }
                    }
                    for (EnumConstantDeclaration member : enumDeclaration.getEntries())
                    {
                        List<AnnotationExpr> annotations = member.getAnnotations();
                        if (annotations != null)
                        {
                            annotations.clear();
                        }
                    }
                }
            }
        }

        private static void cleanUpInterfaces(String interfaceName, List<? extends BodyDeclaration> types)
        {
            for (BodyDeclaration type : types)
            {
                cleanUpInterface(type, interfaceName);
                if (type instanceof TypeDeclaration)
                {
                    List<BodyDeclaration> members = ((TypeDeclaration) type).getMembers();
                    if (members == null)
                    {
                        continue;
                    }
                    for (BodyDeclaration body : members)
                    {
                        if (body instanceof ClassOrInterfaceDeclaration)
                        {
                            cleanUpInterface(body, interfaceName);
                            cleanUpInterfaces(interfaceName, ((ClassOrInterfaceDeclaration) body).getMembers());
                        }
                    }
                }
            }
        }

        private static void cleanUpInterface(BodyDeclaration typeDeclaration, String interfaceName)
        {
            if (typeDeclaration instanceof ClassOrInterfaceDeclaration)
            {
                List<ClassOrInterfaceType> interfaceTypes = ((ClassOrInterfaceDeclaration) typeDeclaration).getImplements();
                if (interfaceTypes == null)
                {
                    return;
                }
                List<ClassOrInterfaceType> toBeRemove = new ArrayList<ClassOrInterfaceType>();
                for (ClassOrInterfaceType interfaceType : interfaceTypes)
                {
                    if (interfaceType.toString().equals(interfaceName))
                    {
                        toBeRemove.add(interfaceType);
                    }
                }
                interfaceTypes.removeAll(toBeRemove);
            }
        }

        private static void optimizeImport(CompilationUnit cu)
        {
            List<ImportDeclaration> toBeRemove = new ArrayList<ImportDeclaration>();
            if (cu.getImports() == null)
            {
                return;
            }
            for (ImportDeclaration importDeclaration : cu.getImports())
            {
                String importPackageName = importDeclaration.getName().toString();
                if (importPackageName.startsWith("java.io")
                        || importPackageName.startsWith("javax.xml.datatype")
                        || importPackageName.startsWith("java.util")
                        || importPackageName.startsWith("java.math")
                        || importPackageName.startsWith("java.text"))
                {
                    continue;
                }
                toBeRemove.add(importDeclaration);
            }
            cu.getImports().removeAll(toBeRemove);
        }

        public static List<File> listFilesForFolder(final File folder, List<File> result)
        {
            for (final File fileEntry : folder.listFiles())
            {
                if (fileEntry.isDirectory())
                {
                    listFilesForFolder(fileEntry, result);
                }
                else
                {
                    if (result == null)
                    {
                        result = new ArrayList<File>();
                    }
                    result.add(fileEntry);
                }
            }
            return result;
        }

        private static void removeMethod(CompilationUnit cu, String methodName)
        {
            List<TypeDeclaration> types = cu.getTypes();
            for (TypeDeclaration type : types)
            {
                List<BodyDeclaration> members = type.getMembers();
                cleanUp(methodName, type, members);

                if (type.getAnnotations() != null)
                {
                    type.getAnnotations().clear();
                }
                type.setJavaDoc(null);
                type.setComment(null);
            }
        }

        private static void cleanUp(String methodName, BodyDeclaration type, List<BodyDeclaration> members)
        {
            List<BodyDeclaration> membersToRemove = new ArrayList<BodyDeclaration>();
            for (BodyDeclaration member : members)
            {
                try
                {
                    member.setJavaDoc(null);
                    member.setComment(null);
                    if (member.getAnnotations() != null)
                    {
                        member.getAnnotations().clear();
                    }
                    if (member instanceof MethodDeclaration && methodName.equals(((MethodDeclaration) member).getName()))
                    {
                        membersToRemove.add(member);
                    }
                    if (member instanceof ClassOrInterfaceDeclaration)
                    {
                        cleanUp(methodName, member, ((ClassOrInterfaceDeclaration) member).getMembers());
                    }
                }
                catch (Exception e)
                {
                    System.out.println(e.getMessage());
                }
            }
            if (type instanceof TypeDeclaration)
            {
                ((TypeDeclaration) type).getMembers().removeAll(membersToRemove);
            }
            else if (type instanceof ClassOrInterfaceDeclaration)
            {
                ((ClassOrInterfaceDeclaration) type).getMembers().removeAll(membersToRemove);
            }
            else if (type instanceof EnumDeclaration)
            {
                ((EnumDeclaration) type).getMembers().removeAll(membersToRemove);
            }
        }


        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)
                    {
                        MethodDeclaration method = (MethodDeclaration) member;
                        changeMethod(method);
                    }
                }
            }
        }

        private static void changeMethod(MethodDeclaration n)
        {
            // change the name of the method to upper case
            n.setName(n.getName().toUpperCase());

            // create the new parameter
            Parameter newArg = ASTHelper.createParameter(ASTHelper.INT_TYPE, "value");

            // add the parameter to the method
            ASTHelper.addParameter(n, newArg);
        }
    }

答案 1 :(得分:0)

如果删除doOldThing()的主体:

doOldThing() {
}

然后内联该方法,它应该在任何地方消失。如果您想要通过调用doNewThing()替换它:

doOldThing() {
    doNewThing();
}

然后内联。