1

我正在使用 com.sun.codemodel 生成我的类并添加 JSR303 注释。这工作正常,除非我想添加 @Pattern.List 注释。

field.annotate(Pattern.class).param("regexp", "some_expression");

这是当前生成的:

@Pattern(regexp = "first_expression", message = "first.Pattern.message")
@Pattern(regexp = "second_expression", message = "second.Pattern.message")
@Pattern(regexp = "third_expression", message = "third.Pattern.message")

这就是我想要生成的

@Pattern.List({
  @Pattern(regexp = "first_expression", message = "first.Pattern.message")
  @Pattern(regexp = "second_expression", message = "second.Pattern.message")
  @Pattern(regexp = "third_expression", message = "third.Pattern.message")
})

有人知道这是怎么做到的吗?

4

1 回答 1

3

假设您想要 @PatternList(list = {@Pattern...}) 而不是您需要使用该paramArray()方法:

JDefinedClass testme = codeModel._class("Testme");

JAnnotationUse patternListAnnotation = testme.annotate(Pattern.List.class);
JAnnotationArrayMember list = patternListAnnotation.paramArray("value");

list.annotate(Pattern.class).param("regexp", "first_expression").param("message", "first.Pattern.message");
list.annotate(Pattern.class).param("regexp", "second_expression").param("message", "second.Pattern.message");
list.annotate(Pattern.class).param("regexp", "third_expression").param("message", "third.Pattern.message");

输出以下内容:

@Pattern.List({
    @Pattern(regexp = "first_expression", message = "first.Pattern.message"),
    @Pattern(regexp = "second_expression", message = "second.Pattern.message"),
    @Pattern(regexp = "third_expression", message = "third.Pattern.message")
})
public class Testme {
}

这应该与示例代码中提示的字段相同。

于 2013-04-11T17:22:25.170 回答