在java中使用instanceof Void

时间:2015-12-13 06:50:06

标签: java class void typeof

我想使用void java的类型,但我不能。这是一个我的代码,它是所有具有@TraceLog注释

的方法的一个方面
  @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
         }
}

作为编码规则不应按名称比较类http://cwe.mitre.org/data/definitions/486.html),我尝试使用(returnType instanceof Void)但我在eclipse中遇到这两个编译时错误:

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

我想知道如何解决它?!

1 个答案:

答案 0 :(得分:2)

您可以使用

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

}

示例:

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

会打印

java.lang.Void