2

我正在尝试@JsonTypeInfo在编译期间使用 AST 将注释添加到我的类中。

要添加的注释应该是(以类为例):

@JsonTypeInfo(use=JsonTypeInfo.Id.CLASS, include=JsonTypeInfo.As.PROPERTY, property="className")

其中JsonTypeInfo.Id定义为:

public enum Id {
    NONE(null),
    CLASS("@class"),
    MINIMAL_CLASS("@c"),
    NAME("@type"),
    CUSTOM(null)
    ;
}

JsonTypeInfo.As定义为:

public enum As {
    PROPERTY,
    WRAPPER_OBJECT,
    WRAPPER_ARRAY,
    EXTERNAL_PROPERTY
    ;
}

都在JsonTypeInfo课堂上。

要添加注释,我有一个函数setJson(),如下所示:

public static void setJson(ClassNode cn)
{
    AnnotationNode an = new AnnotationNode( new ClassNode(com.fasterxml.jackson.annotation.JsonTypeInfo.class));

    an.addMember("use", new ConstantExpression(JsonTypeInfo.Id.CLASS));
    an.addMember("include", new ConstantExpression(JsonTypeInfo.As.PROPERTY));
    an.addMember("property", new ConstantExpression("className"));

    cn.addAnnotation(an);
}

但是,property好像只设定成员没有问题。当我跑完剩下的时间时,我会收到类似的错误

"Expected enum value for attribute use in @com.fasterxml.jackson.annotation.JsonTypeInfo"

如何在 AST 转换期间正确传递枚举值?尝试直接传递值(即使用CLASS1)不起作用。

从这里查看其他Expression类:http: //groovy.codehaus.org/api/org/codehaus/groovy/ast/expr/Expression.html,我想也许FieldExpression可以完成这项工作,但我没能让它工作。

4

1 回答 1

3

在 AST 浏览器中查找带有注释的类JsonTypeInfo(如上面的示例注释),您将获得:

use: org.codehaus.groovy.ast.expr.PropertyExpression@7f78be49 [
         object: org.codehaus.groovy.ast.expr.ClassExpression@5014ec00[
                     type: com.fasterxml.jackson.annotation.JsonTypeInfo$Id
         ]
         property: ConstantExpression[CLASS]
     ]

这让我相信:

an.addMember("use", new ConstantExpression(JsonTypeInfo.Id.CLASS));

应该:

an.addMember("use", new PropertyExpression(
                      new ClassExpression( JsonTypeInfo.Id ),
                      new ConstantExpression( JsonTypeInfo.Id.CLASS ) ) )

但我还没有测试过,可能是在胡说八道:-/

于 2013-07-24T12:08:05.850 回答