How to convert AST to JDT Java model

霸气de小男生 提交于 2019-12-02 00:38:45

This is not really possible. ICompilationUnits are part of the java model, which means that it is part of a Java project somewhere and has a full classpath, a package, a package root, etc. All you are doing is creating a parse tree of some text that is not connected to any java project.

If you can be more specific about what your goal is, it might be the case that you don't really need any IType and IMethod instances.

Or, if you really do need instances of these types, then you will need to generate IProjects, add a java nature to it, and then populate it with files. Your best bet is to see how the JDT test infrastructure works.

Take a look at this file: https://github.com/eclipse/eclipse.jdt.core/blob/master/org.eclipse.jdt.core.tests.builder/src/org/eclipse/jdt/core/tests/builder/TestingEnvironment.java

and how it is used throughout the test framework.

Instead of geting an instance of ICompilationUnit You can use the AST Visitor pattern to visit the Method Declaration nodes & Type Declaration nodes and get the IMethod and IType objects as follows:

compilationUnit.accept(new ASTVisitor() {

    public boolean visit(MethodDeclaration node) {                                                  
        IMethod iMethod = (IMethod) node.resolveBinding().getJavaElement();                                             
        return true;
    }

    public boolean visit(TypeDeclaration node) {                                                   
        IType iType = (IType) node.resolveBinding().getJavaElement();                                                   
        return true;
    }
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!