【AOP】案例:使用环绕通知对原始方法进行修改

47 阅读1分钟
@Component
@Aspect
public class DataAdvice {
    @Pointcut("execution(boolean com.itheima.service.*Service.*(*,*))")
    private void servicePt() {
    }

    @Around("DataAdvice.servicePt()")
    public Object trimStr(ProceedingJoinPoint pjp) throws Throwable {
        Object[] args = pjp.getArgs();
        for (int i = 0; i < args.length; i++) {
            //判断参数是不是字符串
//            if(args[i].getClass().equals(String.class)){
//                args[i] = args[i].toString().trim();
//            }
            if (args[i] instanceof String) {
                args[i] = ((String) args[i]).trim();
            }
        }
        // 记得最后将修改后的数据放回原方法
        return pjp.proceed(args);
    }
}

其中,fori不能改成foreach

for(Object o : args) {
    if (o instanceof String) {
        o = ((String) o).trim();
    }
}

In Java's enhanced for-loop (also known as foreach loop), you cannot modify the items of the collection or array directly through the loop variable. The loop variable in the enhanced for-loop is effectively read-only, and any attempt to modify it will not affect the original collection or array.