2015-06-01 4 views
1

У меня проблема с AnnotationProcessor.Аннотация Обработчик

Первый мой исходный код:

@SupportedAnnotationTypes("*") 
@SupportedSourceVersion(SourceVersion.RELEASE_8) 
public class TreeAnnotationProcessor extends AbstractProcessor{ 

    private Trees trees; 
    private Tree tree; 

    @Override 
    public synchronized void init(ProcessingEnvironment processingEnv) { 
    super.init(processingEnv); 
    trees = Trees.instance(processingEnv); 
    } 

    @Override 
    public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { 
    for (Element element : roundEnv.getRootElements()) { 
     tree = trees.getTree(element); 
    } 

    return true; 
    } 

    public Tree getTree() { 
    return tree; 
    } 
} 

Это Annotationprocessor Соберите дерево компилятора. В этом Процессе все прекрасно. Если я вызову funtion getTree после процесса компиляции, Дерево не будет завершено. Все дети Дерева (Узел) ушли.

... 
JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, null, null, null, compilationUnits); 
TreeAnnotationProcessor treeAnnotationProcessor = new TreeAnnotationProcessor(); 
task.setProcessors(Collections.singletonList(treeAnnotationProcessor)); 
task.call(); 
Tree tree = treeAnnotationProcessor.getTree(); 
... 

Благодарим за любую помощь.

ответ

1

Я нашел решение. Дерево-интерфейс реализуется классом com.sun.tools.javac.tree.JCTree. Этот класс реализует метод clone-Method. Когда я использую этот метод, клон завершается после процесса компиляции:

@SupportedAnnotationTypes("*") 
@SupportedSourceVersion(SourceVersion.RELEASE_8) 
public class TreeAnnotationProcessor extends AbstractProcessor{ 

    private Trees trees; 
    private Tree tree; 

    @Override 
    public synchronized void init(ProcessingEnvironment processingEnv) { 
    super.init(processingEnv); 
    trees = Trees.instance(processingEnv); 
    } 

    @Override 
    public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { 
    for (Element element : roundEnv.getRootElements()) { 
     tree = trees.getTree(element); 

     try { 
     Method cloneMethod = tree.getClass().getMethod("clone"); 
     Object cloneTree = cloneMethod.invoke(tree); 
     this.tree = (Tree) cloneTree; 
     } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { 
     e.printStackTrace(); 
     } 
    } 

    return true; 
    } 

    public Tree getTree() { 
    return tree; 
    } 
} 
Смежные вопросы