Get variable name by using FieldDeclaration

When using visitor pattern to visit a FieldDeclaration node, you may want to get the variable name the node contains. It is natural to think about a method called “getName()”, but this method does not exist in FieldDeclaration class.

The following code shows how you can get the field name or variable name in a class. First of all, we need to get all the fragments by using “fragments()” method, and then get the first fragment it returns by “get(0)”. We know the first element would be VariableDeclarationFragment, but need to first verify its type for security reasons. Then we can use “getName()” method from VariableDeclarationFragment to get the declared variable name.

final CompilationUnit parse = parse(unit);
 
            parse.accept(new ASTVisitor() {
				public boolean visit(MethodDeclaration md){
					System.out.println("-------------method: " + md.getName());
					return false;
				}	
 
				public boolean visit(FieldDeclaration fd){
					Object o = fd.fragments().get(0);
					if(o instanceof VariableDeclarationFragment){
						String s = ((VariableDeclarationFragment) o).getName().toString();
						if(s.toUpperCase().equals(s))
						System.out.println("-------------field: " + s);
					}
 
					return false;
				}
			});

Leave a Comment