Skip to content

Do not apply var when the generic return type needs the declared type - #1187

Merged
timtebeek merged 4 commits into
openrewrite:mainfrom
jevanlingen:fix/use-var-for-generic-return-type
Aug 10, 2026
Merged

Do not apply var when the generic return type needs the declared type#1187
timtebeek merged 4 commits into
openrewrite:mainfrom
jevanlingen:fix/use-var-for-generic-return-type

Conversation

@jevanlingen

@jevanlingen jevanlingen commented Aug 10, 2026

Copy link
Copy Markdown
Contributor

What's changed?

UseVarForObject no longer replaces an explicit type with var when the initializer is a generic method invocation whose type parameter is only inferable from the declared type.

For a method declared as:

<T> T getArgument(int index);

rewriting:

String s = getArgument(0);

to:

var s = getArgument(0);

drops the target type that T was inferred from, so javac infers Object instead of String.

A method is treated as unresolvable when one of its own type parameters occurs in the declared return type but in none of the declared parameter types. That keeps the recipe applying wherever inference does not depend on the declared type:

  • <T> T identity(T t) and <T> T typeToken(Class<T> c) still convert, because T is inferred from the arguments.
  • new A().<String>method() still converts, because an explicit type witness is present.
  • abstract T doIt() on class Outer<T> still converts, because class type parameters resolve through the receiver rather than the assignment target.

Occurrence checking recurses through arrays, type arguments and generic bounds, and candidate declarations are resolved by name and arity across the declaring type, its supertypes and its interfaces. That covers S[], T[][] and List<T> returns, generic methods inherited from a superclass or declared on an interface, and a method type parameter shadowing a class type parameter of the same name.

What's your motivation?

Using var here changes the inferred type of the variable and results in compilation errors or incorrect behaviour. A real world example is Mockito's InvocationOnMock#getArgument(int), declared as <T> T getArgument(int index), which is where this surfaced.

Anything in particular you'd like reviewers to focus on?

Whether the detection is precise enough, in both directions: it should not leave var off a declaration that would compile fine, and it should not let one through that silently infers Object.

The applicability checks in UseVarForObject and UseVarForGenericMethodInvocations are now inlined into their if statements, so the cheap instanceof checks reject a declaration before the type hierarchy walk runs. That is a refactor with no behavioural change.

Have you considered any alternatives or workarounds?

Writing var argument = this.<String>getMethod(); compiles, but it is more verbose and less idiomatic than keeping the explicit type on the variable.

An earlier iteration relied on TypeUtils.findDeclaredMethod failing to match signatures that mention a type parameter. That happened to give the right answer for the common cases, but it was incidental rather than intended, and it broke for generic methods declared on a generic type such as interface Cache<K> { <T> T get(K key); }.

Any additional context

Tests added: genericMethod, genericMethodDeclaredOnInterface, genericMethodDeclaredOnGenericInterface, genericMethodInheritedFromSuperclass, genericMethodReturningArray, genericMethodReturningMultiDimensionalArray and genericMethodShadowingClassTypeParameter as not applicable; typeToken, genericMethodWithTypeParameters, genericMethodInferredFromArgument and genericMethodInferredFromWildcardBoundedArgument as applicable. The pre-existing genericType was renamed to classLevelGenericType to distinguish it from the method level cases.

Original fix by @jevanlingen; the detection refinements and tests are review follow-ups.

@github-project-automation github-project-automation Bot moved this to In Progress in OpenRewrite Aug 10, 2026
@jevanlingen jevanlingen changed the title Fix UseVarForObject with generic method return types Fix bug in UseVarForObject recipe where method return an unresolved generic type Aug 10, 2026
@jevanlingen jevanlingen changed the title Fix bug in UseVarForObject recipe where method return an unresolved generic type Fix bug in UseVarForObject recipe where method returns an unresolved generic type Aug 10, 2026
@MBoegers

Copy link
Copy Markdown
Contributor

👋 hi @jevanlingen good to see you, and thanks for adding another boundary here

jevanlingen and others added 4 commits August 10, 2026 14:40
Determine whether the return type variable is declared by the method
itself via `getDeclaredFormalTypeNames()`, rather than by comparing its
name against the declaring class' type parameters. This also covers a
method type variable shadowing a class type variable of the same name.

Unwrap array return types repeatedly, so that multi dimensional arrays
such as `<T> T[][] method()` are detected as well.

Only resolve the method declaration when the cheaper checks have not
already rejected the declaration, as the lookup walks the supertype and
interface hierarchy.
`TypeUtils.findDeclaredMethod` cannot match a signature whose declared
parameters mention a type variable, as the invocation's parameter types
are resolved while the declaration's are not. Generic methods declared on
a generic type, such as `interface Cache<K> { <T> T get(K key); }`, were
therefore never found and slipped past the check.

Look up candidate declarations by name and arity across the declaring
type, its supertypes and its interfaces instead, and treat a method as
unresolvable when one of its own type parameters occurs in the declared
return type but in none of the declared parameter types. Occurrence
checking recurses through arrays, type arguments and generic bounds.
Inline the conditions into their `if` statements, such that the cheaper
checks can reject a declaration before the more expensive ones run.
@timtebeek
timtebeek force-pushed the fix/use-var-for-generic-return-type branch from c02c3b5 to fadb2cd Compare August 10, 2026 12:42
@timtebeek timtebeek changed the title Fix bug in UseVarForObject recipe where method returns an unresolved generic type Do not apply var when the generic return type needs the declared type Aug 10, 2026
@timtebeek
timtebeek merged commit 7099ad3 into openrewrite:main Aug 10, 2026
1 of 2 checks passed
@github-project-automation github-project-automation Bot moved this from In Progress to Done in OpenRewrite Aug 10, 2026
@timtebeek

Copy link
Copy Markdown
Member

Yes thanks for contributing again; great to see you here. Hope you'll have fun running this at scale there! :)

@jevanlingen
jevanlingen deleted the fix/use-var-for-generic-return-type branch August 10, 2026 16:59
mergify Bot added a commit to robfrank/linklift that referenced this pull request Aug 20, 2026
…41.0 to 3.42.0 [skip ci]

Bumps [org.openrewrite.recipe:rewrite-migrate-java](https://github.com/openrewrite/rewrite-migrate-java) from 3.41.0 to 3.42.0.
Release notes

*Sourced from [org.openrewrite.recipe:rewrite-migrate-java's releases](https://github.com/openrewrite/rewrite-migrate-java/releases).*

> 3.42.0
> ------
>
> What's Changed
> --------------
>
> * Adopt upstream XML trailing-comment formatting by [`@​timtebeek`](https://github.com/timtebeek) in [openrewrite/rewrite-migrate-java#1180](https://redirect.github.com/openrewrite/rewrite-migrate-java/pull/1180)
> * Add mapping for CheckForNull to JSpecify annotation by [`@​zbynek`](https://github.com/zbynek) in [openrewrite/rewrite-migrate-java#1179](https://redirect.github.com/openrewrite/rewrite-migrate-java/pull/1179)
> * Skip `UseSetOf`/`UseListOf` for `HashSet`/`ArrayList` subclasses by [`@​timtebeek`](https://github.com/timtebeek) in [openrewrite/rewrite-migrate-java#1182](https://redirect.github.com/openrewrite/rewrite-migrate-java/pull/1182)
> * Avoid hardcoded patch version in UpdateSdkManTest by [`@​timtebeek`](https://github.com/timtebeek) in [openrewrite/rewrite-migrate-java#1183](https://redirect.github.com/openrewrite/rewrite-migrate-java/pull/1183)
> * Only add the Mockito surefire agent configuration when asked, and keep it minimal by [`@​timtebeek`](https://github.com/timtebeek) in [openrewrite/rewrite-migrate-java#1184](https://redirect.github.com/openrewrite/rewrite-migrate-java/pull/1184)
> * Make subpackage recursion explicit in the Jackson JAX-RS JSON rename by [`@​timtebeek`](https://github.com/timtebeek) in [openrewrite/rewrite-migrate-java#1185](https://redirect.github.com/openrewrite/rewrite-migrate-java/pull/1185)
> * Add the Mockito agent properties goal in its own execution by [`@​MBoegers`](https://github.com/MBoegers) in [openrewrite/rewrite-migrate-java#1186](https://redirect.github.com/openrewrite/rewrite-migrate-java/pull/1186)
> * Derive SDKMAN test versions from the candidate list by [`@​timtebeek`](https://github.com/timtebeek) in [openrewrite/rewrite-migrate-java#1188](https://redirect.github.com/openrewrite/rewrite-migrate-java/pull/1188)
> * Do not apply `var` when the generic return type needs the declared type by [`@​jevanlingen`](https://github.com/jevanlingen) in [openrewrite/rewrite-migrate-java#1187](https://redirect.github.com/openrewrite/rewrite-migrate-java/pull/1187)
> * Cover legacy Bouncy Castle artifacts and their API changes by [`@​timtebeek`](https://github.com/timtebeek) in [openrewrite/rewrite-migrate-java#1189](https://redirect.github.com/openrewrite/rewrite-migrate-java/pull/1189)
> * Add jakarta.validation-api dependency when migrating com.sun.istack.NotNull by [`@​steve-aom-elliott`](https://github.com/steve-aom-elliott) in [openrewrite/rewrite-migrate-java#1190](https://redirect.github.com/openrewrite/rewrite-migrate-java/pull/1190)
>
> New Contributors
> ----------------
>
> * [`@​zbynek`](https://github.com/zbynek) made their first contribution in [openrewrite/rewrite-migrate-java#1179](https://redirect.github.com/openrewrite/rewrite-migrate-java/pull/1179)
>
> **Full Changelog**: <openrewrite/rewrite-migrate-java@v3.41.0...v3.42.0>


Commits

* [`1238ceb`](openrewrite/rewrite-migrate-java@1238ceb) OpenRewrite recipe best practices
* [`01d0fe8`](openrewrite/rewrite-migrate-java@01d0fe8) Add `jakarta.validation-api` dependency when migrating `com.sun.istack.NotNul...
* [`33354b5`](openrewrite/rewrite-migrate-java@33354b5) Cover legacy Bouncy Castle artifacts and their API changes ([#1189](https://redirect.github.com/openrewrite/rewrite-migrate-java/issues/1189))
* [`6c648a5`](openrewrite/rewrite-migrate-java@6c648a5) Update Gradle wrapper to 9.7.0
* [`7099ad3`](openrewrite/rewrite-migrate-java@7099ad3) Do not apply `var` when the generic return type needs the declared type ([#1187](https://redirect.github.com/openrewrite/rewrite-migrate-java/issues/1187))
* [`ccfa7b0`](openrewrite/rewrite-migrate-java@ccfa7b0) Derive SDKMAN test versions from the candidate list ([#1188](https://redirect.github.com/openrewrite/rewrite-migrate-java/issues/1188))
* [`96e8647`](openrewrite/rewrite-migrate-java@96e8647) [Auto] SDKMAN! Java candidates as of 2026-08-10T1102
* [`26f898e`](openrewrite/rewrite-migrate-java@26f898e) Add the Mockito agent properties goal in its own execution ([#1186](https://redirect.github.com/openrewrite/rewrite-migrate-java/issues/1186))
* [`d82dd47`](openrewrite/rewrite-migrate-java@d82dd47) OpenRewrite recipe best practices
* [`55f2e93`](openrewrite/rewrite-migrate-java@55f2e93) Make subpackage recursion explicit in the Jackson JAX-RS JSON rename ([#1185](https://redirect.github.com/openrewrite/rewrite-migrate-java/issues/1185))
* Additional commits viewable in [compare view](openrewrite/rewrite-migrate-java@v3.41.0...v3.42.0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Archived in project

Development

Successfully merging this pull request may close these issues.

3 participants