To update the above answer to the latest version of JavaParser:
CompilationUnit cu = JavaParser.parse("public class Login {\n" +
"\n" +
" private Keyword browser;\n" +
" private String pageTitle = \"Login\";\n" +
"}\n");
for (TypeDeclaration<?> typeDec : cu.getTypes()) {
for (BodyDeclaration<?> member : typeDec.getMembers()) {
member.toFieldDeclaration().ifPresent(field -> {
for (VariableDeclarator variable : field.getVariables()) {
//Print the field's class typr
System.out.println(variable.getType());
//Print the field's name
System.out.println(variable.getName());
//Print the field's init value, if not null
variable.getInitializer().ifPresent(initValue -> System.out.println(initValue.toString()));
}
});
}
}
and a way to get to the field declarations without as much hassle is...
cu.findAll(FieldDeclaration.class).forEach(field -> {
field.getVariables().forEach(variable -> {
//Print the field's class typr
System.out.println(variable.getType());
//Print the field's name
System.out.println(variable.getName());
//Print the field's init value, if not null
variable.getInitializer().ifPresent(initValue -> System.out.println(initValue.toString()));
});
});
The functional difference between the two is that the first one only looks in the top level class, and the second one will also look in nested classes.