2

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.

Community
  • 1
  • 1
Patryk
  • 1,421
  • 8
  • 21

3 Answers3

2

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.

Andrew Eisenberg
  • 28,387
  • 9
  • 92
  • 148
1

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;
    }
});
Unni Kris
  • 3,081
  • 4
  • 35
  • 57
  • As andrew has noted above, in order to resolve bindings the Java class has to be part of a Java project, else the bindings will be returned as null. – Unni Kris Apr 09 '13 at 08:49
0

According to https://www.eclipse.org/articles/article.php?file=Article-JavaCodeManipulation_AST/index.html this is possible with an ASTRewrite. Haven't tried it myself yet, but it looks quite involved.

FelixM
  • 1,496
  • 1
  • 9
  • 19