【问题标题】:Use instanceof Void in java在 java 中使用 instanceof Void
【发布时间】:2025-12-27 23:00:17
【问题描述】:

我想使用 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 <?>

我想知道我该如何解决它?!

【问题讨论】:

    标签: java class void typeof


    【解决方案1】:

    你可以使用

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

    例子:

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

    会打印

    java.lang.Void
    

    【讨论】:

    • 这可能是提问者所要求的,但我认为实际问题涉及小写-v void(就像提问者尝试的字符串比较一样)。鉴于 Void 是最终的,Void.class.isAssignableFrom 也没有任何意义——只需检查相等性。
    • 作为 Jeffrey Bosboom 评论的扩展,我想补充一点,给定一个 Method 对象 m 表示一个 void 方法,调用 Void.class.isAssignableFrom(m.getReturnValue()) 将返回 false,而小写void 将返回 true。