TreeMaker how to write return null statement

295 views Asked by At

like this code

public boolean equals(Object o) {
   return null;
}

i want use treeMaker write return null statement, but i dont know how to do this.

1

There are 1 answers

0
biubiupiu On

I made a mistake in this question, primitive can not return null.

return null statement can gengrated by like this code

JCTree.JCStatement aNull = treeMaker.Return(treeMaker.Literal(TypeTag.BOT, null));

for example

    public String equal(Object o) {
        return null;
    }

    public JCTree.JCMethodDecl generateEqualMethod(JCTree.JCClassDecl classDecl) {
        JCTree.JCModifiers publicModifier = treeMaker.Modifiers(Flags.PUBLIC);
        JCTree.JCExpression returnType = treeMaker.Ident(names.fromString("java"));
        returnType = treeMaker.Select(returnType, names.fromString("lang"));
        returnType = treeMaker.Select(returnType, names.fromString("String"));
        Name method = names.fromString("equal");
        JCTree.JCExpression ObjectExpr = treeMaker.Ident(names.fromString("java"));
        ObjectExpr = treeMaker.Select(ObjectExpr, names.fromString("lang"));
        ObjectExpr = treeMaker.Select(ObjectExpr, names.fromString("Object"));
        JCTree.JCVariableDecl param = 
        treeMaker.VarDef(treeMaker.Modifiers(Flags.PARAMETER),
                names.fromString("o"),
                ObjectExpr,
                null);
        param.pos = classDecl.pos;
        List<JCTree.JCVariableDecl> params = List.of(param);

        List<JCTree.JCStatement> statement = List.nil();
        JCTree.JCStatement aNull = treeMaker.Return(treeMaker.Literal(TypeTag.BOT, null));
        statement = statement.append(aNull);
        JCTree.JCBlock block = treeMaker.Block(0, statement);
        JCTree.JCMethodDecl methodDecl = treeMaker.MethodDef(publicModifier, method, returnType, List.nil(), params, List.nil(), block, null);
        System.out.println(methodDecl);
        return methodDecl;
    }