java自定义注解

自定义注解

一、什么是注解(Annotation)?

注解也叫元数据,是一种代码级别的说明。 是 java5.0 引入的一种注释机制 ,与类、接口、枚举是在统一层次,他可以声明在类、属性、方法、局部变量、方法参数等前面,对这些数据进行说明、注释。

二、自定义注解的声明
1、 元注解

作用: 元注解就是负责注解其他注解 。

1.1 @Target

表明该注解可以应用的java元素类型

target类型描述
CONSTRUCTOR表示注解能用于构造器
FIELD表示注解能用于域
LOCAL_VARIABLE表示注解能用于局部变量
METHOD表示注解能用于方法
PACKAGE表示注解能用于包
PARAMETER表示注解能用于方法参数
TYPE表示注解能用于描述类、接口、或枚举声明
1.2 @Retention

表明该注解的生命周期

生命周期类型方法描述
SOURCE在源文件中有效(即源文件保留)
CLASS在class文件中有效(即class保留)默认值
RUNTIME在运行时有效(即运行时保留)
1.3 @Document

表明该注解标记的元素可以被Javadoc 或类似的工具文档化

1.4 @Inherited

表明使用了@Inherited注解的注解,所标记的类的子类也会拥有这个注解

2、 注解声明
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface MyAnnotation {
    String name() default "张三";
    String sex();
    int age();
}
3、注解的使用
@MyAnnotation(name = "李四",sex = "男",age = 19)
public class Student {
   public String name;
   public String sex;
   public Integer age;

    public String getName() {
        return name;
    }

    public String getSex() {
        return sex;
    }

    public Integer getAge() {
        return age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", sex='" + sex + '\'' +
                ", age=" + age +
                '}';
    }
}
4、注解的解析
public class Test {

    public static void main(String[] args) throws Exception{

        //获取属性类信息
        Class studentClass=Student.class;

        //判断是否添加注解
        if(studentClass.isAnnotationPresent(MyAnnotation.class)){
            //获取注解信息
            MyAnnotation annotation = (MyAnnotation) 	studentClass.getAnnotation(MyAnnotation.class);
            //创建对象
            Student student = (Student) studentClass.getConstructor().newInstance();
            //获取对象属性数组
            Field[] fields = studentClass.getDeclaredFields();
            for(Field field:fields){
                //禁用访问安全检查
                field.setAccessible(true);
                //获取注解类对象并获取注解属性
                Method method = annotation.getClass().getMethod(field.getName());
                //获取注解属性的值
                Object value = method.invoke(annotation);
                //给注解属性赋值
                field.set(student,value);
            }
            System.out.println(student.toString());
        }else{
            System.out.println("没有该注解");
        }

    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值