在java中使用instanceof Void [英] Use instanceof Void in java

查看:349
本文介绍了在java中使用instanceof Void的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用类型的void java,但我不能。这是一个我的代码,这是一个方面运行后所有方法的 @TraceLog 注释

  @AfterReturning(value =@annotation(log),
returning =returnValue,
argNames =joinPoint,log,returnValue
)$ b b public void afterReturning(最终JoinPoint joinPoint,最终TraceLog日志,
final Object returnValue){

Class<?> returnType =((MethodSignature)joinPoint.getSignature())
.getReturnType();
//它与字符串comperaing工作。但是我想用类型
来写if(void.equals(returnType.getName())){
//做一些日志
}
}

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

 code>  - 不兼容的条件操作数类型< capture#5-of?>和Void 
- 类型Void不是通用的;它不能参数化参数<?>



我想知道如何解决这个问题?

您可以使用

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

}

示例:

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

将打印

  java.lang.Void 


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 ?!

解决方案

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

这篇关于在java中使用instanceof Void的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆