1.元注解
首先我们想要定义自己的注解类,必须先了解元注解.一般要实现自己的注解类,那就需要了解一些常用的元注解.
@Target:注解的作用目标
@Target(ElementType.TYPE)——接口、类、枚举、注解
@Target(ElementType.FIELD)——字段、枚举的常量
@Target(ElementType.METHOD)——方法
@Target(ElementType.PARAMETER)——方法参数
@Target(ElementType.CONSTRUCTOR) ——构造函数
@Target(ElementType.LOCAL_VARIABLE)——局部变量
@Target(ElementType.ANNOTATION_TYPE)——注解
@Target(ElementType.PACKAGE)——包
@Retention:注解的保留位置
RetentionPolicy.SOURCE:这种类型的Annotations只在源代码级别保留,编译时就会被忽略,在class字节码文件中不包含。
RetentionPolicy.CLASS:这种类型的Annotations编译时被保留,默认的保留策略,在class文件中存在,但JVM将会忽略,运行时无法获得。
RetentionPolicy.RUNTIME:这种类型的Annotations将被JVM保留,所以他们能在运行时被JVM或其他使用反射机制的代码所读取和使用。
@Document:说明该注解将被包含在javadoc中
@Inherited:说明子类可以继承父类中的该注解
2.注解类的创建
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Name {
public String value() default "";
}
3.使用类创建
public class Student {
@Name("xiaoming")
private String name;
public String getName() {
setAnnotation();
return name;
}
public void setName(String name) {
this.name = name;
}
//通过反射获取注解类的信息
private void setAnnotation(){
Class<? extends Student> clazz = this.getClass();
//判断处理注解在类上
if (clazz.isAnnotationPresent(Name.class)) {
//获取注解类
Name annotation = (Name) clazz.getAnnotation(Name.class);
try {
//设值
Field field = clazz.getDeclaredField("name");
field.setAccessible(true);
field.set(this, annotation.value());
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return;
}
//判断处理注解在属性上
Field[] declaredFields = clazz.getDeclaredFields();
for (Field declaredField : declaredFields) {
Name annotation = declaredField.getAnnotation(Name.class);
if (null == annotation) {
continue;
}
declaredField.setAccessible(true);
try {
declaredField.set(this, annotation.value());
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
}
4.运行测试
main方法执行
Student s = new Student();
System.out.println(s.getName());
运行结果:
以上纯粹是为了测试注解类的使用,实际生产中还是要根据自己的情况去使用自定义注解,如有错误,欢迎指出,谢谢.