Reputation: 1484
I've got generic method Foo.foo()
:
class Foo {
static native T <T> foo();
}
Bar bar = Foo.foo();
What I need is to replace calls to this method using AspectJ. The problem is that to return a value of type T from the aspect, I need to know what T is. How can I do this with AspectJ?
Here is one solution I've tried:
Object around() : call(* Foo.foo(..)) {
Class target = ((MethodSignature) thisJoinPoint.getSignature()).getReturnType();
System.out.println("class = " + class);
}
It returns Object
as the class of return type. How can I determine that call to foo()
should actually return instance of Bar
?
Upvotes: 1
Views: 6168
Reputation: 8261
I have not checked it, but I believe this should work.
Method method = ((MethodSignature) thisJoinPoint.getSignature()).getMethod();
Type type = method.getGenericReturnType();
System.out.println("type = " + type);
Please take a look at the javadoc at here: Method#getGenericReturnType()
Upvotes: 7
Reputation: 4937
At runtime you won't be able to discern that. The substitution of Bar for T is erased at compile-time, and so would be unavailable to your advice.
If MethodSignature offered something like getGenericReturnType(), the best it'd be able to tell you is that the return type of Foo.foo() is T. It'd be interrogating the generics info baked into the class file for Foo, rather than being able to figure out from a runtime call what the intended type was.
Another question for you: how does Foo.foo() know to return Bar?
Upvotes: 0