使用Java AST将项目中的所有文字字符串重构为常量

时间:2018-01-09 14:17:08

标签: java string refactoring constants abstract-syntax-tree

我有大量需要解析的源文件,并提取所有字符串文字,并将它们作为java常量放入类中(类似于这个问题Extract all string from a java project进程,我想跟随下一步:

  • 读取目录(src目录)并转到每个文件
  • 在每个文件上,首先阅读并检查
  • 中是否有任何文字字符串
  • 在真实情况下,使用ast来导入常量类。不仅仅是 跳到下一个文件
  • 导入后,在源文件中使用ast重构所有字符串 文字变量
  • 最后,将新的变量添加到常量类

    我已经开发了一些功能,使用了我发现的一些复制/粘贴代码(与AST完全相似),但我不知道如何做2º和4º步骤

有人可以帮助我吗?无论如何反而更好地做AST(我不能在eclipse上使用externalize string fuction)?

pd:对不起我的英语,非母语人士

编辑:`

public class Main {
    public static void parse(final String str) {
        final ASTParser parser = ASTParser.newParser(AST.JLS3);
        parser.setSource(str.toCharArray());
        parser.setKind(ASTParser.K_COMPILATION_UNIT);
        String identificador="dasiodas ";
        final CompilationUnit cu = (CompilationUnit) parser.createAST(null);
        cu.recordModifications();
        cu.accept(new ASTVisitor() {

            Set names = new HashSet();
            int contadormod=0;


            public boolean visit(VariableDeclarationFragment node) {
            /*  if(node.toString().contains("="))
                int ptoken=node.toString().i

            if(ptoken!=-1){
            String declaracion = node.toString().substring(ptoken);
                if(declaracion.contains("new String ")&&declaracion.indexOf("\"")!=0){
                    declaracion=declaracion.substring(declaracion.indexOf("\""), declaracion.lastIndexOf("\""));
                    String identificador=node.getName().toString()+"ct";
                    System.out.println("he pasod al if ");
                }
            }
            //ASTRewrite rewrite= ASTRewrite.create(node.getAST());
             //rewrite.replace(node,rewrite.getAST().newAssignment(), null);

                String prueba = "mi prueba ";
                SimpleName name = node.getName();
                System.out.println(node.toString()+" esto es el inicializador");
                this.names.add(name.getIdentifier());
                System.out.println("Declaration of '" + name + "' at line"
                        + cu.getLineNumber(name.getStartPosition()));
                */
                return false; // do not continue 
            }





            public boolean visit(SimpleName node) {
                if (this.names.contains(node.getIdentifier())) {
                    System.out.println("Usage of '" + node + "' at line "
                            + cu.getLineNumber(node.getStartPosition()));
                }
                return true;
            }
            public boolean visit (StringLiteral node){
            System.out.println(node.getLiteralValue()+" string literal ");
            ASTRewrite rewrite= ASTRewrite.create(node.getAST());
            rewrite.replace(node,
                    rewrite.getAST().new.newName("Constant"), null);
            // 2
            //node.setStructuralProperty(SimpleType.NAME_PROPERTY, rewrite
              //      .getAST().newSimpleName("int")); // 2



                rewrite = ASTRewrite.create(cu.getAST());
               // cu.recordModifications();
                //cu.accept(new XQASTVisitor());
                Document doc =new Document(str);
                //IDocument doc = new IDocument();
                //cu.re
                TextEdit edits = cu.rewrite(doc, null);
                try {
                    edits.apply(doc);
                } catch (MalformedTreeException e) {
                    e.printStackTrace();
                } catch (org.eclipse.jface.text.BadLocationException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                return false;
            }

        });

    }

    //read file content into a string
    public static String readFileToString(String filePath) throws IOException {
        StringBuilder fileData = new StringBuilder(1000);
        BufferedReader reader = new BufferedReader(new FileReader(filePath));

        char[] buf = new char[10];
        int numRead = 0;
        while ((numRead = reader.read(buf)) != -1) {
            System.out.println(numRead);
            String readData = String.valueOf(buf, 0, numRead);
            fileData.append(readData);
            buf = new char[1024];
        }

        reader.close();

        return  fileData.toString();    
    }

    //loop directory to get file list
    public static void ParseFilesInDir() throws IOException{
        File dirs = new File(".");
        String dirPath = dirs.getCanonicalPath() + File.separator+"src"+File.separator;

        File root = new File(dirPath);
        //System.out.println(rootDir.listFiles());
        File[] files = root.listFiles ( );
        String filePath = null;

         for (File f : files ) {
             filePath = f.getAbsolutePath();
             if(f.isFile()){
                 parse(readFileToString(filePath));
             }
         }
    }

    public static void main(String[] args) throws IOException {
        ParseFilesInDir();
    }

`

0 个答案:

没有答案