Use instanceof Void in java

这一生的挚爱 提交于 2019-12-07 21:03:28

问题


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:


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


来源:https://stackoverflow.com/questions/34248693/use-instanceof-void-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!