Java Parser遍历类的方法

时间:2018-06-19 22:38:35

标签: java parsing generated-code

我想知道是否存在诸如Java解析器(如解析器xml)之类的东西。我的意思是从这样的字符串

String javaToParse = "public class x{void foo(){...} void baar(){...}}"

例如,我可以从foo或所有方法的主体等中获取主体(以字符串格式)。

我有类似的东西

public class Some {
    @PostConstruct
    public void init1() {
        //some to do
    }
    @PostConstruct
    public void init2() {
        //some to do2
    }
    @PostConstruct
    public void init3() {
        //some to do3
    }
//..more..
}

这里有一个或多个@PostConstruct 此类是自动生成的,我无法手动对其进行修改。

我想迭代所有@PostConstruct方法,并将他所有的主体放在一个@Postcontruct方法中,并导出到文件中并得到:

public class Some {
    @PostConstruct
    public void init() {
        //some to do
        //some to do2
        //some to do3
    }
}

我看到可以将文件获取为String并使用fors手动操作并手动搜索,但是可能有自由主义者可以这样做。 编辑:

通过JavaParser解决 如果有人在这里有类似的问题,我的解决方案:

public static void createUniquePostContruct(File InputFile,File outputFile) throws FileNotFoundException {
        //get class to modified
        FileInputStream in = new FileInputStream(ficheroEntradaJava);
        // parse the file
        CompilationUnit cu = JavaParser.parse(in);
        //store methods with @PostContruct
        List<MethodDeclaration> methodsPost = new ArrayList<>();
        //iterate over all class' methods
        cu.accept(new VoidVisitorAdapter<Void>() {
            @Override
            public void visit(MethodDeclaration method, Void arg) {
                //if this method has @PostConstruct
                if (method.getAnnotationByName("PostConstruct").isPresent()) {
                    methodsPost .add(method);
                }
            }
        }, null);
        //delete all methods with @PostConstruct
        methodsPost.forEach((method) -> method.remove());
        //add a unique @PostConstruct method using body of anothers @PostConstruct methods
        MethodDeclaration uniqueMethodPostConstruct = new MethodDeclaration(EnumSet.of(Modifier.PUBLIC), new VoidType(), "init");
        uniqueMethodPostConstruct.addAnnotation("PostConstruct");
        BlockStmt bodyUniqueMethodPostConstruct= new BlockStmt();
        metodosPost.forEach(method-> {
            method.getBody().get().getStatements().forEach(statement -> {
                bodyUniqueMethodPostConstruct.addStatement(statement);
            });
        });
        metodoUnicoPostConstruct.setBody(bodyUniqueMethodPostConstruct);
        //get main class and put our method
        Optional<ClassOrInterfaceDeclaration> clazz = cu.getClassByName(ficheroEntradaJava.getName().split("\\.")[0]);
        clazz.get().addMember(uniqueMethodPostConstruct);

        System.out.println(cu.toString());

        //write to file
        try (PrintWriter out = new PrintWriter(outputFile)) {
            out.println(cu.toString());
        } catch (FileNotFoundException ex) {
            Logger.getLogger(ParserMetodos.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

0 个答案:

没有答案