NutzCN Logo
问答 求解 能否把数组转变成可变长参数 (弱智的问题 ^_^)
发布于 2562天前 作者 SniperZj 4693 次浏览 复制 上一个帖子 下一个帖子
标签:

String methodName = "xxxx"
Object[] objects = joinPoint.getArgs();
能把 objects 变成 可变长参数 调用如下方法吗
public Method getMethod(String name, Class<?>... parameterTypes){
//.....
}

10 回复

强转为Class<?>[]就就可以传过去了

@Before("webLog()")
public void doBefore(JoinPoint joinPoint) {
startTime.set(System.currentTimeMillis());

// 接收到请求,记录请求内容
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();


String classMethod = joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName() + ",params:" + Arrays.toString(joinPoint.getArgs());
// 记录下请求内容

Object[] objects = joinPoint.getArgs();
logger.info("ARGS : " + Arrays.toString(joinPoint.getArgs()));

//test1(joinPoint,objects);//获取targetClass 下的所有方法进行遍历
    //test2(joinPoint,objects);  //根据方法名和参数列表直接定位方法

}

public static String test1(JoinPoint joinPoint, Object[] objects) {
String description = "";
try {
String targetName = joinPoint.getTarget().getClass().getName();
String methodName = joinPoint.getSignature().getName();
Object[] arguments = joinPoint.getArgs();
Class targetClass;
targetClass = Class.forName(targetName);
//获取targetClass 下的所有方法进行遍历
Method[] methods = targetClass.getMethods();
for (Method method : methods) {
if (method.getName().equals(methodName)) {
Class[] classes = method.getParameterTypes();
if (classes.length == arguments.length) {
if (method.getAnnotation(xxx.class) != null) {
description = method.getAnnotation(xxx.class).description();
}
break;
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return description;
}

public static String test2(JoinPoint joinPoint, Object[] objects) {
String description = "";
try {
String targetName = joinPoint.getTarget().getClass().getName();
String methodName = joinPoint.getSignature().getName();
Object[] arguments = joinPoint.getArgs();
Class targetClass;
targetClass = Class.forName(targetName);
//根据方法名和参数列表直接定位方法
Method method = targetClass.getMethod(methodName, (Class<?>[]) objects );
Class[] classes = method.getParameterTypes();
if (classes.length == arguments.length) {
if (method.getAnnotation(xxx.class) != null) {
description = method.getAnnotation(xxx.class).description();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return description;
}
我想改造 test2 方法 但是 强转还是报错
java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.Class;

@Before("webLog()")
 public void doBefore(JoinPoint joinPoint) {
 startTime.set(System.currentTimeMillis());

// 接收到请求,记录请求内容
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();


String classMethod = joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName() + ",params:" + Arrays.toString(joinPoint.getArgs());
// 记录下请求内容

Object[] objects = joinPoint.getArgs();
logger.info("ARGS : " + Arrays.toString(joinPoint.getArgs()));

//test1(joinPoint,objects);//获取targetClass 下的所有方法进行遍历
    //test2(joinPoint,objects);  //根据方法名和参数列表直接定位方法
}

public static String test1(JoinPoint joinPoint, Object[] objects) {
 String description = "";
 try {
 String targetName = joinPoint.getTarget().getClass().getName();
 String methodName = joinPoint.getSignature().getName();
 Object[] arguments = joinPoint.getArgs();
 Class targetClass;
 targetClass = Class.forName(targetName);
 //获取targetClass 下的所有方法进行遍历
 Method[] methods = targetClass.getMethods();
 for (Method method : methods) {
 if (method.getName().equals(methodName)) {
 Class[] classes = method.getParameterTypes();
 if (classes.length == arguments.length) {
 if (method.getAnnotation(xxx.class) != null) {
 description = method.getAnnotation(xxx.class).description();
 }
 break;
 }
 }
 }
 } catch (Exception e) {
 e.printStackTrace();
 }
 return description;
 }

public static String test2(JoinPoint joinPoint, Object[] objects) {
 String description = "";
 try {
 String targetName = joinPoint.getTarget().getClass().getName();
 String methodName = joinPoint.getSignature().getName();
 Object[] arguments = joinPoint.getArgs();
 Class targetClass;
 targetClass = Class.forName(targetName);
 //根据方法名和参数列表直接定位方法
 Method method = targetClass.getMethod(methodName, (Class<?>[]) objects );
 Class[] classes = method.getParameterTypes();
 if (classes.length == arguments.length) {
 if (method.getAnnotation(xxx.class) != null) {
 description = method.getAnnotation(xxx.class).description();
 }
 }
 } catch (Exception e) {
 e.printStackTrace();
 }
 return description;
 }
我想改造 test2 方法 但是 强转还是报错
java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.Class;

原来是反射,新建个Class数组嘛,然后遍历参数,逐个元素赋值

还想能直接 转呢 还是老实的遍历赋值吧

 /**
     * @param point
     * @return
     */
    private Object getMethodReturnObject(ProceedingJoinPoint point, Object obj) {
        MethodSignature signature = (MethodSignature) point.getSignature();
        // 如果是 ajax 请求,返回方法的返回值
        if (signature.getMethod().getAnnotation(ResponseBody.class) != null) {
            return obj;
        }
        // 如果不是ajax 获取 Model 中的属性
        for (Object o : point.getArgs()) {
            if (o instanceof Model) {
                Model m = (Model) o;
                return m.asMap();
            }
        }
        return obj;// 其他情况
    }

    /**
     * @param point
     * @return
     */
    private String getParameter(ProceedingJoinPoint point) {
        List<Object> target = Lists.newArrayList();

        for (Object obj : point.getArgs()) {
            if (obj instanceof ServletRequest) {
                target.add(((ServletRequest) obj).getParameterMap());
            } else if (obj instanceof ServletResponse || obj instanceof HttpSession || obj instanceof Model) { // response/session/model

            } else {
                target.add(obj);
            }
        }
        return gson.toJson(target);
    }

好吧,贴个完整的:


/** * Created by wizzer on 2016/12/22. */ @Aspect @Component public class SLogAop { @Autowired private SLogService sLogService; private Gson gson = new GsonBuilder() .setDateFormat("yyyy-MM-dd hh:mm:ss") .create(); @Pointcut("@annotation(com.aebiz.app.web.commons.log.annotation.SLog)") public void cutSLog() { } public SLog getSLogCut(JoinPoint joinPoint) throws Exception { String targetName = joinPoint.getTarget().getClass().getName(); String methodName = joinPoint.getSignature().getName(); Object[] arguments = joinPoint.getArgs(); Class targetClass = Class.forName(targetName); Method[] methods = targetClass.getMethods(); SLog target = null; for (Method method : methods) { if (method.getName().equals(methodName)) { Class[] clazzs = method.getParameterTypes(); if (clazzs.length == arguments.length) { target = method.getAnnotation(SLog.class); break; } } } return target; } @Around("cutSLog()") public Object recordSysLog(ProceedingJoinPoint point) throws Throwable { SLog log = getSLogCut(point); Sys_log sysLog = new Sys_log(); sysLog.setUsername(StringUtil.getUsername()); sysLog.setActionTime(DateUtil.getDateTime()); sysLog.setType(log.type()); sysLog.setDescription(log.description()); sysLog.setIp(Lang.getIP(SpringUtil.getRequest())); sysLog.setAction(point.getSignature().getName()); sysLog.setModule(point.getTarget().getClass().getName()); sysLog.setMethodMeta(point.getSignature().toLongString()); sysLog.setParameters(getParameter(point)); StopWatch stopwatch = new StopWatch(); stopwatch.start(); Object obj = null; try { obj = point.proceed(); } catch (Exception e) { stopwatch.stop(); sysLog.setOperationTime(stopwatch.getTotalTimeMillis()); sysLog.setMethodReturn(e.getMessage()); sysLog.setSuccess(false); sLogService.async(sysLog); throw e; } stopwatch.stop(); sysLog.setOperationTime(stopwatch.getTotalTimeMillis()); sysLog.setOpAt((int) (System.currentTimeMillis() / 1000)); sysLog.setOpBy(StringUtil.getUid()); sysLog.setDelFlag(false); if (log.methodReturn()) { Object rObj = getMethodReturnObject(point, obj); sysLog.setMethodReturn(gson.toJson(rObj)); } sLogService.async(sysLog); return obj; } /** * @param point * @return */ private Object getMethodReturnObject(ProceedingJoinPoint point, Object obj) { MethodSignature signature = (MethodSignature) point.getSignature(); // 如果是 ajax 请求,返回方法的返回值 if (signature.getMethod().getAnnotation(ResponseBody.class) != null) { return obj; } // 如果不是ajax 获取 Model 中的属性 for (Object o : point.getArgs()) { if (o instanceof Model) { Model m = (Model) o; return m.asMap(); } } return obj;// 其他情况 } /** * @param point * @return */ private String getParameter(ProceedingJoinPoint point) { List<Object> target = Lists.newArrayList(); for (Object obj : point.getArgs()) { if (obj instanceof ServletRequest) { target.add(((ServletRequest) obj).getParameterMap()); } else if (obj instanceof ServletResponse || obj instanceof HttpSession || obj instanceof Model) { // response/session/model } else { target.add(obj); } } return gson.toJson(target); } }

还是 得 循环 methods 看来不能直接根据methodName 直接获取 Method

添加回复
请先登陆
回到顶部