How to convert AST to JDT Java model

天大地大妈咪最大 提交于 2019-12-02 05:20:12

问题


I am writing unit tests for my plugin that makes use of IType and IMethod interfaces from JDT. To write unit tests I would need to instantiate such interfaces. Answer to this question shows how to create AST model, but I don't know how to convert it into Java model?

My code looks like this:

String source = 

  "package com.test\n" +
  "\n" +
  "import com.test.something;" + 
  "\n" +
  "public class Class{\n" +
  "int sum(int a, int b)\n" +
  "}\n";

ASTParser parser = ASTParser.newParser(AST.JLS4);
parser.setSource(source.toCharArray());
CompilationUnit unit = (CompilationUnit) parser.createAST(null);

So I have an instance of CompilationUnit, but I need an instance of ICompilationUInit, so I can get access to IMethod and IType objects.


回答1:


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.




回答2:


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;
    }
});


来源:https://stackoverflow.com/questions/15813202/how-to-convert-ast-to-jdt-java-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!