Find Java field declarations of type String
Description
To extract all Java field names of type String
is not as straightforward as one might think. A simple pattern like String $F;
would only match fields declared without any modifiers or annotations. However, a pattern like $MOD String $F;
cannot be correctly parsed by tree-sitter.
Use playground pattern debugger to explore the AST
You can use the playground's pattern tab to visualize the AST of class A { $MOD String $F; }
.
field_declaration
$MOD
variable_declarator
identifier: String
ERROR
identifier: $F
Tree-sitter does not think $MOD
is a valid modifier, so it produces an ERROR
.
While the valid AST for code like private String field;
produces different AST structures:
field_declaration
modifiers
type_identifier
variable_declarator
identifier: field
A more robust approach is to use a structural rule that targets field_declaration
nodes and applies a has
constraint on the type
child node to match the type String
. This method effectively captures fields regardless of their modifiers or annotations.
YAML
id: find-field-with-type
language: java
rule:
kind: field_declaration
has:
field: type
regex: ^String$
Example
@Component
class ABC extends Object{
@Resource
private final String with_anno;
private final String with_multi_mod;
public String simple;
}
Contributed by
Inspired by the post discussion