鉴于以下内容:
public class CodeGenerator {
private final static String PACKAGE = "nl.sander.mieras";
private final static String CLASS = "Person";
private final static Class<String> DATA_TYPE = String.class;
private static final String INDEX = "index";
private List<String> columnNames;
public CodeGenerator() {
columnNames = new ArrayList<>();
columnNames.add("personId");
columnNames.add("firstName");
System.out.println(generateClass());
}
private String generateClass() {
final JavaClassSource javaClass = Roaster.create(JavaClassSource.class);
javaClass.setPackage(PACKAGE).setName(CLASS);
int columnCount = -1;
for (String columnName : columnNames) {
columnCount++;
String columnIndex = Integer.toString(columnCount);
javaClass.addProperty(DATA_TYPE, columnName).getField()
.addAnnotation(com.univocity.parsers.annotations.Parsed.class)
.addAnnotationValue(INDEX);
}
return javaClass.toString();
}
}
输出如下:
public class Person {
@Parsed(index = @MISSING)
private String personId;
@Parsed(index = @MISSING)
private String firstName;
public String getPersonId() {
return personId;
}
public void setPersonId(String personId) {
this.personId = personId;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
}
如何使用roaster库向注释添加参数(在本例中为计数器)以获得以下结果?
@Parsed(index = 0)
private String personId;
我尝试了一些没有成功的方法......
使用setAnnotationValue():
javaClass.addProperty(DATA_TYPE, columnName).getField()
.addAnnotation(com.univocity.parsers.annotations.Parsed.class)
.addAnnotationValue(INDEX).setAnnotationValue(columnIndex);
抛出
Exception in thread "main" java.lang.ClassCastException: org.jboss.forge.roaster._shade.org.eclipse.jdt.core.dom.SingleMemberAnnotation cannot be cast to org.jboss.forge.roaster._shade.org.eclipse.jdt.core.dom.NormalAnnotation
at org.jboss.forge.roaster.model.impl.AnnotationImpl.setAnnotationValue(AnnotationImpl.java:597)
at nl.sander.mieras.CodeGenerator.generateClass(CodeGenerator.java:33)
at nl.sander.mieras.CodeGenerator.<init>(CodeGenerator.java:21)
at nl.sander.mieras.Main.main(Main.java:6)
并使用setLiteralValue()方法:
javaClass.addProperty(DATA_TYPE, columnName).getField()
.addAnnotation(com.univocity.parsers.annotations.Parsed.class)
.addAnnotationValue(INDEX).setLiteralValue(columnIndex);
结果:
@Parsed(index = @MISSING(0))
private String personId;
来自https://github.com/forge/roaster/blob/master/tests/src/test/java/org/jboss/forge/test/roaster/model/common/AnnotationTest.java的测试显示了一些用例,但我无法弄清楚如何获得我想要的结果。
答案 0 :(得分:1)
我想你知道4个月后的答案,但......总之它应该是这样的:
property.addAnnotation(annotation)
.setLiteralValue(
"index", "0");
请记住,如果你需要字符串...,那么它有点陌生,因为你需要额外增加“所以它变成了
property.addAnnotation(annotation)
.setLiteralValue(
"index", "\"string-value\"");