给定以下内容:
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中的测试显示了一些用例,但我不知道如何获得所需的结果。
最佳答案
我想您会在4个月后知道答案,但是...总之应该是这样的:
property.addAnnotation(annotation)
.setLiteralValue(
"index", "0");
请记住,如果您需要字符串...,那么这有点陌生,因为您需要添加一个额外的“,以便它成为
property.addAnnotation(annotation)
.setLiteralValue(
"index", "\"string-value\"");