如何使用JavaParser向解析文件添加新方法?

时间:2018-08-27 18:23:19

标签: javaparser

我已经解析了一个Java文件并获得了编译单元

CompilationUnit cu = JavaParser.parse(in);在Java文件中

如何使用此cu添加一些新方法?

我只想在原始类中添加新方法。

3 个答案:

答案 0 :(得分:1)

这是一个有关如何创建方法并将其添加到编译单元的示例:

    // create the type declaration 
    ClassOrInterfaceDeclaration type = cu.addClass("GeneratedClass");

    // create a method
    EnumSet<Modifier> modifiers = EnumSet.of(Modifier.PUBLIC);
    MethodDeclaration method = new MethodDeclaration(modifiers, new VoidType(), "main");
    modifiers.add(Modifier.STATIC);
    method.setModifiers(modifiers);
    type.addMember(method);

    // or a shortcut
    MethodDeclaration main2 = type.addMethod("main2", Modifier.PUBLIC, Modifier.STATIC);

    // add a parameter to the method
    Parameter param = new Parameter(new ClassOrInterfaceType("String"), "args");
    param.setVarArgs(true);
    method.addParameter(param);

    // or a shortcut
    main2.addAndGetParameter(String.class, "args").setVarArgs(true);

    // add a body to the method
    BlockStmt block = new BlockStmt();
    method.setBody(block);

    // add a statement do the method body
    NameExpr clazz = new NameExpr("System");
    FieldAccessExpr field = new FieldAccessExpr(clazz, "out");
    MethodCallExpr call = new MethodCallExpr(field, "println");
    call.addArgument(new StringLiteralExpr("Hello World!"));
    block.addStatement(call);

答案 1 :(得分:0)

在这里,我向一些测试类添加了新的测试方法:

        for (Node childNode : compilationUnit.getChildNodes()) {
        if (childNode instanceof ClassOrInterfaceDeclaration) {
            ClassOrInterfaceDeclaration classOrInterfaceDeclaration = (ClassOrInterfaceDeclaration) childNode;
            MethodDeclaration method = classOrInterfaceDeclaration.addMethod("testingGetterAndSetter", Modifier.PUBLIC);
            method.addMarkerAnnotation("Test");
            NodeList<Statement> statements = new NodeList<>();
            BlockStmt blockStmt = JavaParser.parseBlock(String.format(TestMethod, className));
            method.setBody(blockStmt);
        }
    }

Testmethod包含方法的主体

答案 2 :(得分:0)

创建带有注释的类并向该类添加方法的示例如下。

ClassOrInterfaceDeclaration controllerClass = cu.addClass("SomeClass")
    .setPublic(true)
    .addAnnotation(org.springframework.web.bind.annotation.RestController.class);

MethodDeclaration indexMethod = controllerClass.addMethod("index", Keyword.PUBLIC);
相关问题