我有通用方法Foo.foo()
:
class Foo {
static native T <T> foo();
}
Bar bar = Foo.foo();
我需要的是使用AspectJ替换对此方法的调用。问题是要从方面返回类型T的值,我需要知道T是什么。我如何使用AspectJ做到这一点?
以下是我尝试过的一种解决方案:
Object around() : call(* Foo.foo(..)) {
Class target = ((MethodSignature) thisJoinPoint.getSignature()).getReturnType();
System.out.println("class = " + class);
}
它返回Object
作为返回类型的类。如何确定对foo()
的调用应该实际返回Bar
的实例?
答案 0 :(得分:5)
我没有检查过,但我相信这应该可行。
Method method = ((MethodSignature) thisJoinPoint.getSignature()).getMethod();
Type type = method.getGenericReturnType();
System.out.println("type = " + type);
请在此处查看javadoc:Method#getGenericReturnType()
答案 1 :(得分:0)
在运行时,您将无法辨别出这一点。 Bar for T的替换在编译时被删除,因此您的建议无法使用。
如果MethodSignature提供类似getGenericReturnType()的东西,那么最好能告诉你的是Foo.foo()的返回类型是T.它会查询烘焙到类文件中的泛型信息Foo,而不是能够从运行时调用中找出想要的类型。
另一个问题:Foo.foo()如何知道返回Bar?