2014-10-16 5 views

ответ

2

Да JDT может быть хорошим подходом к решению этой проблемы.

Следующий код предоставит вам представление о том, как сделать то же самое.
(примечание: код не тестировался и не компилируется)

if (javaElement instanceof IMethod) { 

    // Get the compilation unit for traversing AST 
    final ASTParser parser = ASTParser.newParser(AST.JLS4); 
    parser.setSource(javaElement.getCompilationUnit()); 
    parser.setResolveBindings(true); 

    final CompilationUnit compilationUnit = (CompilationUnit) parser.createAST(null); 

    // Record modification - to be later written with ASTRewrite 
    compilationUnit.recordModifications(); 

    // Get AST node for IMethod 
    int methodIndex = javaElement.getCompilationUnit().getSource().indexOf(javaElement.getSource()); 

    ASTNode methodASTNode = NodeFinder.perform(compilationUnit.getRoot(), methodIndex, javaElement.getSource().length()); 

    // Create the annotation 
    final NormalAnnotation newNormalAnnotation = methodASTNode.getAST().newNormalAnnotation(); 
    newNormalAnnotation.setTypeName(methodASTNode.getAST().newName("AnnotationTest")); 

    // Add logic for writing the AST here. 

} 
+1

спасибо за это. Я использовал [annotationUtils] (http://help.eclipse.org/luna/index.jsp?topic=%2Forg.eclipse.jst.ws.jaxws.doc.isv%2Freference%2Fapi%2Forg%2Feclipse%2Fjst% 2Fws% 2Fannotations% 2Fcore% 2Futils% 2FAnnotationUtils.html) из eclipse luna, у которого была простая apis для этого. –