Skip to content
This repository has been archived by the owner on Nov 26, 2021. It is now read-only.

Generic method with "local" return type will fail to resolve getExactReturnType #5

Closed
leonard84 opened this issue Jul 3, 2020 · 3 comments

Comments

@leonard84
Copy link

Hi,

I encountered the following problem:

Given

public class Parent <A> {
  public <T extends Annotation> T getAnnotation(Class<T> clazz) {
    return null
  }
}

public class Child extends Parent<Child> {
}

this call will fail

Method m = Child.getMethod("getAnnotation", Class.class);
GenericTypeReflector.getExactReturnType(m, Child.class);
UnresolvedTypeVariableException: An exact type is requested, but the type contains a type variable that cannot be resolved.
   Variable: T from public java.lang.annotation.Annotation Parent.getAnnotation(java.lang.Class)
   Hint: This is usually caused by trying to get an exact type when a generic method who's type parameters are not given is involved.

The same call does not fail if the containing type is not parameterized.

Method m = Child.getMethod("getAnnotation", Class.class);
GenericTypeReflector.getExactReturnType(m, Class.class);

Furthermore, would it be possible to add a resolveReturnType(Method m, Object[] args) that could return the actual type for such signatures <T extends Annotation> T getAnnotation(Class<T> clazz) when the arguments are given?

@kaqqao
Copy link

kaqqao commented Nov 14, 2021

@leonard84 I believe this is intentional, as the exact return type was requested and could not be determined.
In case you care, I maintain a fork of this project, and it has a family of methods that allow incomplete type resolution.
For this specific case, you could use GenericTypeReflector.getReturnType(m, Class.class) which would return T extends Annotation. From there you could use (the recently added) reduceBounded to get Annotation.
getExactX and getX methods behave identically apart from the latter leaving unresolvable variables as they are. reduceBounded recursively replaces all bounded types (variables, wildcards and captures) with their first bound. Since first bound isn't really a well defined thing, especially for captures, I intend to add an overload that accepts custom strategy for reducing bounds.
I hope that helps.

@leonard84
Copy link
Author

Hi @kaqqao thanks, I'll have a look at your fork then.

@coekie
Copy link
Owner

coekie commented Nov 25, 2021

Thanks @kaqqao.
Yes, use the fork. I'm going to archive this repository.

@coekie coekie closed this as completed Nov 25, 2021
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants