Last active
July 17, 2016 13:34
-
-
Save bdulac/62954848149321f1d39924d1e0405994 to your computer and use it in GitHub Desktop.
Eclipse JDT: get the ASTNode from an IJavaElement
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.eclipse.core.runtime.NullProgressMonitor; | |
import org.eclipse.jdt.core.ICompilationUnit; | |
import org.eclipse.jdt.core.IJavaElement; | |
import org.eclipse.jdt.core.IMember; | |
import org.eclipse.jdt.core.dom.AST; | |
import org.eclipse.jdt.core.dom.ASTNode; | |
import org.eclipse.jdt.core.dom.ASTParser; | |
import org.eclipse.jdt.core.dom.CompilationUnit; | |
/** An AST node <em>resolver</em>. */ | |
public class EclipseASTResolver { | |
/** | |
* Parses the AST node for a specified <em>Java</em> element. | |
* @param javaElement | |
* The <em>Java</em> element to parse the AST node for. | |
* @return The parsed AST node. | |
*/ | |
public ASTNode parseASTNodeForElement(IJavaElement javaElement) { | |
if(javaElement instanceof IMember) { | |
IMember member = (IMember)javaElement; | |
// Fetch the Java model compilation unit | |
ICompilationUnit cUnit = member.getCompilationUnit(); | |
// Note the simple name of the java element in the compilation unit | |
String simpleName = javaElement.getElementName(); | |
// Parse the source | |
// (the language specification version should suit your needs) | |
ASTParser parser = ASTParser.newParser(AST.JLS3); | |
parser.setSource(cUnit); | |
parser.setResolveBindings(true); | |
// Fetch the AST node for the compilation unit | |
ASTNode unitNode = parser.createAST(new NullProgressMonitor()); | |
// It should be an AST compilation unit | |
if(unitNode instanceof CompilationUnit) { | |
CompilationUnit sourceUnit = (CompilationUnit)unitNode; | |
ASTNode elementNode = sourceUnit.findDeclaringNode(simpleName); | |
return elementNode; | |
} | |
} | |
// (you might wish to throw an exception here) | |
return null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment