自定义java注解
用处
1、编译检查
2、反射时可以通过注解来选择某个属性或者方法或者参数
3、可以生成帮助文档(Swagger2)
4、帮助查看代码(@Override)
// 目标放在哪里
@Target({ElementType.FIELD,ElementType.PARAMETER})
// 保留策略 一般使用RUNTIME
@Retention(RetentionPolicy.RUNTIME)
// 是否存入文档
@Documented
public @interface NotNull {
String msg() default "参数不能为空";
}
public enum ElementType {
/** Class, interface (including annotation type), or enum declaration 类,接口(包括注解类型),枚举*/
TYPE,
/** Field declaration (includes enum constants)
属性上使用
*/
FIELD,
/** Method declaration 方法上使用 */
METHOD,
/** Formal parameter declaration 形式参数上使用*/
PARAMETER,
/** Constructor declaration 构造器上使用*/
CONSTRUCTOR,
/** Local variable declaration 局部变量上使用*/
LOCAL_VARIABLE,
/** Annotation type declaration 注解类型使用 */
ANNOTATION_TYPE,
/** Package declaration 包上使用*/
PACKAGE,
/**
* Type parameter declaration 类型参数使用
*/
TYPE_PARAMETER,
/**
* Use of a type 使用类型
*/
TYPE_USE
}
就可以在需要用到注解的地方使用
public String getUserName(@NotNull String id) { }
// 通过反射就能选择 注解上的属性、方法、参数等信息
Parameter[] parameters = signature.getMethod().getParameters();
for (int i = 0; i < parameters.length; i++) {
Parameter parameter = parameters[i];
//Java自带基本类型的参数(例如Integer、String)的处理方式
if (isPrimite(parameter.getType())) {
// 找到@NotNull标注的参数
NotNull notNull = parameter.getAnnotation(NotNull.class);
if (notNull != null && (args[i] == null || "".equals(args[i]) ) ) {
throw new RuntimeException(parameter.toString() + notNull.msg());
}
continue;
}
}