Esto pertenece a la serie de tutoriales Eclipse JDT.
Este ejemplo de código es para insertar una declaración en el código fuente de Java existente utilizando eclipse JDT. Funciona dentro de un complemento.
Por motivos de simplicidad, el siguiente código agrega una declaración de invocación de método llamada «agregar» a la primera línea de un método.
public class Main { public static void main(String[] args) { } public static void add() { int i = 1; System.out.println(i); } } |
El código anterior se convierte en el siguiente:
public class Main { public static void main(String[] args) { add(); } public static void add() { int i = 1; System.out.println(i); } } |
Nuevamente, este es un código completamente funcional probado bajo Eclipse Indigo.
private void AddStatements() throws MalformedTreeException, BadLocationException, CoreException { IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject("testAddComments"); IJavaProject javaProject = JavaCore.create(project); IPackageFragment package1 = javaProject.getPackageFragments()[0]; // get first compilation unit ICompilationUnit unit = package1.getCompilationUnits()[0]; // parse compilation unit CompilationUnit astRoot = parse(unit); // create a ASTRewrite AST ast = astRoot.getAST(); ASTRewrite rewriter = ASTRewrite.create(ast); // for getting insertion position TypeDeclaration typeDecl = (TypeDeclaration) astRoot.types().get(0); MethodDeclaration methodDecl = typeDecl.getMethods()[0]; Block block = methodDecl.getBody(); // create new statements for insertion MethodInvocation newInvocation = ast.newMethodInvocation(); newInvocation.setName(ast.newSimpleName("add")); Statement newStatement = ast.newExpressionStatement(newInvocation); //create ListRewrite ListRewrite listRewrite = rewriter.getListRewrite(block, Block.STATEMENTS_PROPERTY); listRewrite.insertFirst(newStatement, null); TextEdit edits = rewriter.rewriteAST(); // apply the text edits to the compilation unit Document document = new Document(unit.getSource()); edits.apply(document); // this is the code for adding statements unit.getBuffer().setContents(document.get()); } |