Take the 2-minute tour ×

I'm writing an Eclipse Plugin to do some simple code generation. I'm able to grab an IMethod representing the Method I need to modify, but I'm unsure how to actually write additional code in its body. I know this can be done with AST nodes, so is there a way to convert betwen IMethod and MethodDeclaration or something like that?

share|improve this question
add comment

1 Answer

up vote 0 down vote accepted

IMethod is a class of JDT's Java model while MethodDeclaration is a node class of the JDT AST. The Java model has no connection to the AST. But you can use the model to create an AST, typically ICompilationUnit (represents a Java source file) is used, although creating an AST from a string is also possible.

I would suggest checking out this article


Possibly "no direct connection" would have been the better wording. In the JDT FAQ is the following:

How to go from one of IBinding, IJavaElement, ASTNode to another?


From an IJavaElement to an IBinding

If you only need the binding key and not the binding object itself, look for a 'getKey()' method in a subtype of IJavaElement. This method returns the binding key, which can be useful in many situations e.g. see next point. Note that not all subtypes of IJavaElement have a corresponding binding, e.g. IType and IMethod have one but IPackageFragment and IImportContainer do not.

If you really need the binding objects you can use 'org.eclipse.jdt.core.dom.ASTParser.createBindings(IJavaElement[], IProgressMonitor)'. Note that this operation is slightly expensive, compared to just getting the binding key, as the bindings have to be created.

From an IJavaElement to its declaring ASTNode

org.eclipse.jdt.core.dom.CompilationUnit.findDeclaringNode(String) - The string parameter is the binding key, see previous point.

share|improve this answer
Good article, thank you. It was quite easy to search for a method in the java model, so I grabbed an IMethod. I then parsed the ICompilationUnit into an AST, grabbed the mehod declarations from that, and compared their java element (MethodDeclaration.resolvebinding().getJavaElement()) to the original IMethod. When they matched, I knew that MethodDeclaration(AST) corresponded to the original IMethod(JavaModel). I'm sure this isn't the proper way to do this, but it worked. –  user1010080 Oct 18 '12 at 14:58
You are welcome. I have added an excerpt from the JDT FAQ where the method CompilationUnit.findDeclaringNode() is mentioned. Possibly that can simplify your code. –  sevenforce Oct 21 '12 at 9:17
add comment

Your Answer


