asdfghjkl
asdfghjkl

Reputation: 1

How to use JavaParser to add new methods to a parsing file?

I have parsed a java file and get the Compilation Unit

CompilationUnit cu = JavaParser.parse(in); in a java file

How can I add some new methods by using this cu?

I just want to add the new methods in my original class.

Upvotes: 0

Views: 2376

Answers (3)

Arun Saragadam
Arun Saragadam

Reputation: 75

An example of creating a class with annotation and adding a method to that class is as follows.

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

MethodDeclaration indexMethod = controllerClass.addMethod("index", Keyword.PUBLIC);

Upvotes: 0

Ronald
Ronald

Reputation: 336

here i am adding a new test method to some testing classes:

        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);
        }
    }

the Testmethod contains the body of the method

Upvotes: 1

Eslam Ashour
Eslam Ashour

Reputation: 113

This is an example on how you can create a method and add it to your compilation unit:

    // 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);

Upvotes: 4

Related Questions