AspectJ-切入点以匹配具有通用参数的方法 [英] AspectJ - pointcut to match a method that has generic parameters

查看:341
本文介绍了AspectJ-切入点以匹配具有通用参数的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个通用方法,可以接受任何类型作为其参数.
例如,我想要一个切入点,该切入点仅将"String"类型作为其参数来匹配对方法的调用.最终,要求是将执行建议的范围限制为字符串"参数.

I have a generic method that accepts any type as its parameter.
For example, I would like a pointcut that matches the calls made to the method only with 'String' type as its parameter. Ultimately the requirement is to limit the scope which the advices get executed for to 'String' parameters.

这是我的通用类和方法:

Here is my generic class and method:

public class Param<T> {
    public T execute(T s){
        return s;
    }
}

主类:我的应用程序同时使用布尔值和字符串作为参数来调用该方法.

Main class: My app makes calls to the method with both Boolean and String as parameters.

public static void main(String[] args) {
    Param<String> sp = new Param<String>();
    String rs = sp.execute("myString"); //want a joint point

    Param<Boolean> bp = new Param<Boolean>();
    Boolean rb = bp.execute(true); //dont want a joint point
}

以下切入点对String和Boolean参数均有效(实际上适用于任何类型).但是我希望切入点仅在参数类型为String时才拦截方法调用.

Below pointcuts are valid for both String and Boolean parameters (work for any type actually). But I would like a pointcut to intercept method calls only when parameter is of type String.

@Pointcut("call(* com.amazon.auiqa.aspectj.generics.Param.execute(**))")
void param(){}

@Pointcut("execution(Object com.amazon.auiqa.aspectj.generics.Param.execute(Object))")
void param(){}

下面的那些对我不起作用:

Below ones did not work for me:

 @Pointcut("execution(String com.amazon.auiqa.aspectj.generics.Param.execute(String))")
 @Pointcut("call(String com.amazon.auiqa.aspectj.generics.Param.execute(String))")

我想知道是否有可能实现我想在这里实现的目标.我想对方法返回类型做同样的事情.

I was wondering if it is possible to achieve what I want to achieve here. I would like to do the same thing with method return types.

推荐答案

您无法使用AspectJ或任何其他字节码操作库来执行此操作,因为实际上已从已编译的字节码中删除了通用类型信息(从Java 9开始),因此您的通用方法变为public Object execute(Object s),因为类型参数T是无界的.有关更多信息,请参见Java文档中的类型擦除.

You cannot do that with AspectJ, nor with any other bytecode manipulation library as generic type information is actually erased from the compiled bytecode (as of Java 9), so your generic method becomes public Object execute(Object s), since the type argument T is unbounded. See Type Erasure at the Java Documentation for further info.

虽然原始方法签名以元数据的形式保留,但是编译器可以在针对通用代码进行编译时检查是否遵守类型限制,但这在任何情况下都无法帮助您确定实例的通用类型参数.该类的实例被实例化,因为该信息根本不存在.

While the original method signature is preserved in the form of metadata, the compiler can check whether type bounds are respected or not while compiling against generic code, but this will not help you in any way to determine what generic type argument an instance of that class was instantiated with, because that information is simply not present at all.

这篇关于AspectJ-切入点以匹配具有通用参数的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆