开发者

Getting return type of generic method call in AspectJ

开发者 https://www.devze.com 2023-03-21 00:44 出处:网络
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

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.pri开发者_如何学JAVAntln("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?

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号