您的位置:首页 > 编程语言 > Java开发

JAVA 自定义注解并解析

2017-12-08 00:00 309 查看
摘要: JAVA Annotation 自定义注解并解析

Java内置注解有:@Override 重载 ,@Deprecated 弃用 ,@SuppressWarnings 忽略警告

自定义注解特性:

1.不能有参数
2.返回类型局限于原始类型,字符串,枚举,注解,或以上类型构成的数组
3.可包含默认值
4.可包含与其绑定的元注解,元注解为注解提供信息,有四种元注解类型:@Documented,@Target,@Inherited,@Retention

a. @Documented – 表示使用该注解的元素应被javadoc或类似工具文档化
b. @Target – 表示支持注解的程序元素的种类,值有TYPE, METHOD, CONSTRUCTOR, FIELD等。如果Target元注解不存在,那么该注解就可以使用在任何程序元素之上。
c. @Inherited – 表示一个注解类型会被自动继承,如果用户在类声明的时候查询注解类型,同时类声明中也没有这个类型的注解,那么注解类型会自动查询该类的父类,这个过程将会不停地重复,直到该类型的注解被找到为止,或是到达类结构的顶层Object
d. @Retention – 表示注解类型保留时间的长短,值SOURCE, CLASS, 以及RUNTIME。

例如:自定义注解@Entity 和 @Column,以及解析方法

@Documented
@Retention(RUNTIME)
@Target(TYPE)
public @interface Entity {
String tableName() default "";
}

@Documented
@Retention(RUNTIME)
@Target(FIELD)
public @interface Column {

int lenght() default 0;

String name() default "";

String type() default "";

boolean primaryKey() default false;

boolean allowNull() default true;

boolean unique() default false;

}

public static void main(String[] args) {
Class<?> clazz = null;
try {
clazz = Class.forName("com.oak.service.Member");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}

Entity entity = clazz.getAnnotation(Entity.class);
//Annotation[] anns = clazz.getDeclaredAnnotations();
System.out.println("Table name=="+entity.tableName());
for (Field field : clazz.getDeclaredFields()) {
System.out.println("Field name=="+field.getName()+",Field type=="+field.getType().getSimpleName());
Column c = field.getAnnotation(Column.class);
if(c!=null)
System.out.println(c.lenght());

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Java annotation