GroovyAST在编译时添加通用字段

时间:2016-07-29 22:26:56

标签: generics groovy abstract-syntax-tree bytecode groovyc

我想在编译时为某些类添加一个通用字段。为了达到这个目的,我通过遵循官方documentation来实现我自己的AST注释和转换类,并使用AST注释注释所需的类。

但是我在编译时遇到了这个错误:

  

org.codehaus.groovy.control.MultipleCompilationErrorsException:启动失败:   /home/.../groovy/Sample.groovy:-1:转换使用包含ClassNode java.util.HashSet的泛型直接用于字段x。你不应该这样做。请创建一个引用旧ClassNode的新ClassNode,并使用新的ClassNode而不是旧的ClassNode。否则,编译器将在OpenJDK中的TypeResolver中创建错误的描述符和潜在的NullPointerException。如果这不是您自己的行为,请将此错误报告给转换的作者。    @ line -1,第-1列。

我犯了错误吗?

示例代码

例如,假设我想在HashSet<Long>注释注释的每个类中添加一个名为x的{​​{1}}字段。

我的AST注释类:

MyAST

我的AST转换课程:

@Retention(RetentionPolicy.SOURCE)
@Target(ElementType.TYPE)
@GroovyASTTransformationClass(classes = [MyASTTransformation.class])
public @interface MyAST {
}

示例注释类:

@CompileStatic
@GroovyASTTransformation(phase = CompilePhase.SEMANTIC_ANALYSIS)
public class MyASTTransformation implements ASTTransformation {

@Override
public void visit(ASTNode[] nodes, SourceUnit sourceUnit) {
     ClassNode clazz = (ClassNode) nodes[1];
     ClassNode longHashSetClass = new ClassNode(HashSet.class);
     longHashSetClass.setGenericsTypes([new GenericsType(new ClassNode(Long.class))] as GenericsType[]);
     FieldNode field = new FieldNode("x", FieldNode.ACC_PRIVATE, longHashSetClass, clazz, new ConstantExpression(null));
     clazz.addField(field);
 }
}

注意

当我删除行@MyAST public class Sample { } 时,一切正常,但longHashSetClass.setGenericsTypes([new GenericsType(new ClassNode(Long.class))] as GenericsType[]);的类型在运行时为x而不是HashSet

1 个答案:

答案 0 :(得分:3)

您应该使用public void createPdf(String dest) throws IOException { //Initialize PDF document PdfDocument pdf = new PdfDocument(new PdfWriter(dest)); // Initialize document Document document = new Document(pdf); Table table = new Table(new float[]{2, 1, 1}); table.setWidthPercent(80); table.setHorizontalAlignment(HorizontalAlignment.CENTER); table.setTextAlignment(TextAlignment.CENTER); table.addCell(new Cell(1, 3).add("Cell with colspan 3")); table.addCell(new Cell(2, 1).add("Cell with rowspan 2") .setTextAlignment(TextAlignment.RIGHT)); table.addCell("row 1; cell 1"); table.addCell("row 1; cell 2"); table.addCell("row 2; cell 1"); table.addCell("row 2; cell 2"); Cell cell = new Cell() .add(new Paragraph("Left").setTextAlignment(TextAlignment.LEFT)) .add(new Paragraph("Center")) .add(new Paragraph("Right").setTextAlignment(TextAlignment.RIGHT)); table.addCell(cell); cell = new Cell().add("Middle") .setVerticalAlignment(VerticalAlignment.MIDDLE); table.addCell(cell); cell = new Cell().add("Bottom") .setVerticalAlignment(VerticalAlignment.BOTTOM); table.addCell(cell); document.add(table); document.close(); } ClassHelper来创建ClassNode:

GenericUtils