问题
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