Reputation: 823
i am parsing java source code with Eclipse AST parser and successfully can locate local variable as VariableDeclarationStatement
. Problem is i need variable as ILocalVariable
for usage of refactoring. In this case getJavaElement()
doesn't work since local variables arent in Java Model. Any idea how to get it from there?
Upvotes: 0
Views: 539
Reputation: 31
I encountered the same problem, but none of the solutions above worked for me. After some research I found a solution, which works for me:
// reconcile corresponding compilation unit
compilationUnit.reconcile(ICompilationUnit.NO_AST, false, null, null);
// parse code and get the elements
IJavaElement[] elements =
((ICodeAssist) compilationUnit).codeSelect(startPos + length, 0);
// if there is an element and its an instance of ILocalVariable.
if (anElements.length > 0 && anElements[0] instanceof ILocalVariable) {
return (ILocalVariable) anElements[0];
}
So in conclusion: You need the starting position and the length of the variable. (startPos
+ length
). And the compilation unit, which I already had.
Upvotes: 1
Reputation:
You can try the following:
Having programmed in hand VariableDeclarationStatement variable
You can code as:
IVariableBinding binding = variable.resolveBinding();
ILocalVariable local = (ILocalVariable) binding.getJavaElement();
Upvotes: 1
Reputation: 8230
IVariableBinding binding = variable.resolveBinding();
if (!binding.isField() && !binding.isEnumConstant() && !binding.isParameter())
{
ILocalVariable local = (ILocalVariable) binding.getJavaElement();
}
Upvotes: 0
Reputation: 28757
Note that I haven't tried this myself, but looking at the source code, the below mentioned steps should work:
setResolveBindings(true)
VariableDeclarationFragments
by calling VariableDeclarationStatement.fragments()
.resolveBinding()
.getJavaElement()
.Upvotes: 0
Reputation: 28757
Here is another option. Create the ILocalVariable object yourself. The org.eclipse.jdt.internal.core.LocalVariable
is internal API (and the constructor has changed between 3.6 and 3.7).
The constructor (in Eclipse 3.6) takes the following arguments:
public LocalVariable(
JavaElement parent,
String name,
int declarationSourceStart,
int declarationSourceEnd,
int nameStart,
int nameEnd,
String typeSignature,
org.eclipse.jdt.internal.compiler.ast.Annotation[] astAnnotations)
Most of these parameters should be fairly straight forward and available directly from the VariableDeclarationStatement
. Note that typeSignature
is not the fully qualified name, but rather the type signatures generated from org.eclipse.jdt.core.Signature
.
Upvotes: 0