简体   繁体   中英

Getting return type of generic method call in AspectJ

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 ?

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()

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM