Use instanceof Void in java

2019-05-20 06:39发布

I want to use the type of void java but I can't. Here is a my code which is an aspect run after to all methods which have @TraceLog annotations

  @AfterReturning(value = "@annotation(log)", 
       returning = "returnValue", 
       argNames = "joinPoint, log, returnValue"
      )
    public void afterReturning(final JoinPoint joinPoint, final TraceLog log,
            final Object returnValue) {

            Class<?> returnType = ((MethodSignature) joinPoint.getSignature())
            .getReturnType();
           //It works when comperaing with string. But I want to write it with type of
           if ("void".equals(returnType.getName()) ) {
            //Do some log
         }
}

As a coding rule Classes should not be compared by name (http://cwe.mitre.org/data/definitions/486.html), I tried to use (returnType instanceof Void) but I face these two compile time errors in eclipse:

- Incompatible conditional operand types Class<capture#5-of ?> and   Void
- The type Void is not generic; it cannot be parameterized with arguments <?>

I wonder how can I fix it ?!

1条回答
淡お忘
2楼-- · 2019-05-20 07:22

You can use

if (Void.class.isAssignableFrom (returnType)) {

}

Example :

Class<?> returnType = Void.class;
if (Void.class.isAssignableFrom (returnType)) {
  System.out.println (returnType.getName ());
}

would print

java.lang.Void
查看更多
登录 后发表回答