0

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

cu = JavaParser.parse(in);java文件中的编译 单元

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

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

4

3 回答 3

4

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

    // 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);
于 2018-10-08T10:24:47.133 回答
1

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

        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 包含方法的主体

于 2019-06-18T09:36:40.577 回答
0

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

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

MethodDeclaration indexMethod = controllerClass.addMethod("index", Keyword.PUBLIC);
于 2020-09-25T00:42:12.870 回答