I use for logging AOP, Spring, log4j. There is a need to display the input parameters of each method marked @Loggable as a string. Below is the code. If the input parameter is an array of primitives, then you have to do a long check, presented in the arrayToString () method. If you just do a cast (Object []), then a ClassCastomException occurs. Is it possible to simplify arrayToString () using generic or some other way? thank

@Aspect public class LoggingAspect { private static final Logger logger = LogManager.getLogger(); @Around("@annotation(logger.Loggable)") public Object logMethod(ProceedingJoinPoint joinPoint) { if (joinPoint.getArgs() != null) { Object[] arrayArgs = convertArgsToString(joinPoint.getArgs()); } return returnValue; } private Object[] convertArgsToString(Object[] args) { for (int i = 0; i < args.length; i++) { if (args[i] != null && args[i].getClass().isArray()) { args[i] = arrayToString(args[i]); } } return args; } private String arrayToString(Object array){ String result; if (array instanceof boolean[]) { result = Arrays.toString((boolean[])array); } else if (array instanceof byte[]) { result = Arrays.toString((byte[])array); } else if (array instanceof short[]) { result = Arrays.toString((short[])array); } else if (array instanceof char[]) { result = Arrays.toString((char[])array); } else if (array instanceof int[]) { result = Arrays.toString((int[])array); } else if (array instanceof long[]) { result = Arrays.toString((long[])array); } else if (array instanceof float[]) { result = Arrays.toString((float[])array); } else if (array instanceof double[]) { result = Arrays.toString((double[])array); } else { result = Arrays.toString((Object[])array); } return result; } } 

    1 answer 1

    Unfortunately, in java you cannot convert an array of primitives into an array of objects, therefore, the only way to solve your problem without using third-party libraries is described by you.

    However, the Apache Commons Lang library contains the ArrayUtils class, in which, in turn, there is a static method toString (Object array), which solves your problem. That is, using this library, you can rewrite the code in the following way:

     @Aspect public class LoggingAspect { private static final Logger logger = LogManager.getLogger(); @Around("@annotation(logger.Loggable)") public Object logMethod(ProceedingJoinPoint joinPoint) { if (joinPoint.getArgs() != null) { Object[] arrayArgs = convertArgsToString(joinPoint.getArgs()); } return returnValue; } private Object[] convertArgsToString(Object[] args) { for (int i = 0; i < args.length; i++) { if (args[i] != null && args[i].getClass().isArray()) { args[i] = ArrayUtils.toString(args[i]); } } return args; } } 
    • Thanks for the detailed response - William Blake