如何删除JDefinedClass上的注释

时间:2016-01-19 10:31:05

标签: java annotations sun-codemodel jcodemodel

我正在jsonschema2pojo中编写一个自定义注释器,以便调整此代码生成器如何使用Jackson注释注释生成的类。

为了简化用例,我手头有一个JClass,它已经是

的注释
JsonInclude( JsonInclude.Include.NON_NULL )

我希望将其替换为:

JsonInclude( JsonInclude.Include.NON_EMPTY )

我正在使用com.sun.codemodel:codemodel:2.6

如果我尝试添加注释而不删除原始注释

JDefinedClass clazz = ...; // the class we want to annotate
clazz.annotate(JsonInclude.class).param( "value", JsonInclude.Include.NON_EMPTY );

然后我收到一个编译错误,说我的模式不能超过@JsonInclude。

所以我尝试在添加注释之前删除注释

JCodeModel codeModel = new JCodeModel();
JClass jsonInclude = codeModel.ref(JsonInclude.class);
clazz.annotations().remove( jsonInclude );

但是注释集合是不可修改的......

有没有办法从JDefinedClass中删除特定的注释?

1 个答案:

答案 0 :(得分:2)

查看JCodeModel源代码是正确的,没有办法在不通过反射破坏类(访问私有成员变量)的情况下删除注释:

public Collection<JAnnotationUse> annotations() {
    if(this.annotations == null) {
        this.annotations = new ArrayList();
    }

    return Collections.unmodifiableCollection(this.annotations);
}

我建议您在应用程序的更高级别尝试确定哪个注释适合(NON_NULLNON_EMPTY),然后才需要定义JDefinedClass。对于我编写的代码生成器,我通常会在进入代码生成阶段之前准备好一个模型,这有助于防止在指定之后决定生成什么。

相关问题