Java 注解

2017-04-19  本文已影响0人  醉疯觞

元注解

@Target

表示该注解可以用于什么地方。可能的ElementType参数包括:

CONSTRUCTOR:构造器的声明
FIELD:域声明(包括enum)示例
LOCAL_VARIABLE:局部变量声明
METHOD:方法声明
PACKAGE:包声明
PARAMETER:参数声明
TYPE:类、接口(包括注解类型)或enum声明
@Retention

表示该注解在什么级别保存该注解信息。可选的RetentionPolicy参数包括:

SOURCE:注解将被编译器丢弃
CLASS:注解在class文件中可用,但会被VM丢弃
RUNTIME:VM将在运行期也保留注释,因此可以通过反射机制读取注解的信息
@Documented

将此注解包含在Javadoc中。

@Inherited

允许子类继承父类中的注解。

注解元素

注解元素可用的类型:

*  所有基本类型(int,float,boolean等)
*  String
*  Class
*  Annotation
*  以上类型的数组

也不允许使用任何包装类型

默认值限制

元素不能有不确定的值。也就是说,元素必须要么具有默认值,要么在使用注解时提供元素的值。
其次,对于非基本类型的元素,无论是在源代码中声明时,或是在注解接口定义默认值时,都不能以 null 作为其值。

利用反射进行注解判断

(JoinPoint joinPoint) throws Exception {

String targetName = joinPoint.getTarget().getClass().getName();
String methodName = joinPoint.getSignature().getName();
Class<?> targetClass = Class.forName(targetName);
Method[] methods = targetClass.getMethods();
Annotation[][] notNull = new Annotation[][]{};
for (Method method : methods) {
    if (method.getName().equals(methodName)) {
        notNull = method.getParameterAnnotations();
        break;
    }
}
Object[] args = joinPoint.getArgs();
for (int i = 0; i < notNulls.length; i++) {
    Object param = args[i];
    for (Annotation anno : notNulls[i]) {
        if(ParamNotNull.class.equals(anno.annotationType())){
            ParamNotNull notNull = (ParamNotNull)anno;
            String[] fieldNames = notNull.fieldNames();
            String paramName = notNull.paramName();
            
            if(CommonUtils.isEmpty(param)) {
                throw new BizException(RestCode.SUBMIT_PARAMETERS_EXCEPTION.getRespCode()+""
                        , RestCode.SUBMIT_PARAMETERS_EXCEPTION.getRespMsg()+";参数"+paramName+":为空");
            }else {
                for (String fieldName : fieldNames) {
                    logger.debug("fieldName:"+fieldName);
                    Field field = ReflectHelper.getFieldByFieldName(param, fieldName); 
                    field.setAccessible(true);
                    Object value = field.get(param);

                    if(CommonUtils.isEmpty(value)) {
                        throw new BizException(RestCode.SUBMIT_PARAMETERS_EXCEPTION.getRespCode()+""
                                , RestCode.SUBMIT_PARAMETERS_EXCEPTION.getRespMsg()+";参数"+paramName+"的"+fieldName+"属性为空");
                    }
                    field.setAccessible(false);
                }
            }
        }
    }
}
上一篇 下一篇

猜你喜欢

热点阅读