Search code examples
javaeclipseeclipse-jdtabstract-syntax-tree

How to convert AST to JDT Java model


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.


Solution

  • 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.