Semgrep matches class names for metavariable-type checks
Introduced 2026-03-31 · score 0.96
HOW TO USE IT
When a rule needs to match a class name in a method call and check that name’s type, match `$C.getInstance(...)` and apply `metavariable-type` to `$C`.
rules:
- id: class-name-type-check
languages: [java]
message: Matched class name with the requested type
severity: WARNING
patterns:
- pattern: $C.getInstance(...)
- metavariable-type:
metavariable: $C
type: <type-expression>patterns:
- pattern: $C.getInstance(...)
- metavariable-type:
metavariable: $C
types:
- <type-expression-1>
- <type-expression-2>WHY THIS HELPS
Write a rule that matches a class name in a method call and checks that class's type.
BEFORE THIS CHANGE
The release note says this match-and-type-check workflow became possible in v1.157.0; it does not specify the prior alternative.
REQUIREMENTS AND LIMITATIONS
- Version: 1.157.0
- pattern (required): Code expression to match; here `$C.getInstance(...)`.
- metavariable-type.metavariable (required): Metavariable whose type is checked; here `$C`.
- metavariable-type.type (required): One type expression to check against. Mutually exclusive with `types`.
- metavariable-type.types (required): List of type expressions to check against. Mutually exclusive with `type`.
- metavariable-type.language: Optional language string in the schema; its effect is not documented in the source inspected.
- languages (required): Rule language list; choose the target language for the code being matched.
FIRST-PARTY EVIDENCE
- https://github.com/semgrep/semgrep/releases/tag/v1.157.0
- https://github.com/semgrep/semgrep-interfaces/blob/main/rule_schema_v1.yaml
- https://docs.semgrep.dev/writing-rules/rule-syntax
Check the installed version and the source before using it. Entry JSON