How can I use the java Eclipse Abstract Syntax Tree in a project outside Eclipse? (ie not an eclipse plugin)

后端 未结 2 950
青春惊慌失措
青春惊慌失措 2020-12-04 14:41

How can I use the java Eclipse Abstract Syntax Tree in a project outside Eclipse? (ie not an eclipse plugin)

All the Eclipse AST examples that I\'ve seen are for ecl

2条回答
  •  青春惊慌失措
    2020-12-04 15:15

    Below is the code I used to do this given a Java 1.5 file. I'm very new to this and spent today browsing around, and trying things out to get the code below working.

    public void processJavaFile(File file) {
        String source = FileUtils.readFileToString(file);
        Document document = new Document(source);
        ASTParser parser = ASTParser.newParser(AST.JLS3);
        parser.setSource(document.get().toCharArray());
        CompilationUnit unit = (CompilationUnit)parser.createAST(null);
        unit.recordModifications();
    
        // to get the imports from the file
        List imports = unit.imports();
        for (ImportDeclaration i : imports) {
            System.out.println(i.getName().getFullyQualifiedName());
        }
    
        // to create a new import
        AST ast = unit.getAST();
        ImportDeclaration id = ast.newImportDeclaration();
        String classToImport = "path.to.some.class";
        id.setName(ast.newName(classToImport.split("\\.")));
        unit.imports().add(id); // add import declaration at end
    
        // to save the changed file
        TextEdit edits = unit.rewrite(document, null);
        edits.apply(document);
        FileUtils.writeStringToFile(file, document.get());
    
        // to iterate through methods
        List types = unit.types();
        for (AbstractTypeDeclaration type : types) {
            if (type.getNodeType() == ASTNode.TYPE_DECLARATION) {
                // Class def found
                List bodies = type.bodyDeclarations();
                for (BodyDeclaration body : bodies) {
                    if (body.getNodeType() == ASTNode.METHOD_DECLARATION) {
                        MethodDeclaration method = (MethodDeclaration)body;
                        System.out.println("name: " + method.getName().getFullyQualifiedName());
                    }
                }
            }
        }
    }
    

    This requires the following libraries:

    commons-io-1.4.jar
    org.eclipse.jdt.core_xxxx.jar
    org.eclipse.core.resources_xxxx.jar
    org.eclipse.core.jobs_xxxx.jar
    org.eclipse.core.runtime_xxxx.jar
    org.eclipse.core.contenttype_xxxx.jar
    org.eclipse.equinox.common_xxxx.jar
    org.eclipse.equinox.preferences_xxxx.jar
    org.eclipse.osgi_xxxx.jar
    org.eclipse.text_xxxx.jar
    

提交回复
热议问题