Java注解作用介绍、原注解及其简单应用

一、注解是什么?

注解( Annotation) , 也叫元数据。-种代码级别的说明。它是JDK1.5及以后版本引入的一个特性,与类、接口、枚举是在同一个层次。它可以声明在包、类、字段、方法、局部变量、方法参数等的前面,用来对这些元素进行说明,注释。

二、作用分类

  1. 编写文档:通过代码里标识的注解生成文档[生成文档doc文档]
  2. 代码分析:通过代码里标识的注解对代码进行分析[使用反射]【程序员主要操作】
  3. 编译检查:通过代码里标识的注解让编译器能够实现基本的编译检查[Override]

三、JDK预定义的注解

//清除IDEA警告
@SuppressWarnings("all")
//标记过时方法,比如:date.getYear()
@Deprecated
//检查被该注解标记的方法是否继承父类或接口
@Override

四、自定义注解

/**
 * 元注解
 */
@Target({ElementType.TYPE,ElementType.METHOD}) //描述当前注解能够作用的位置
@Retention(RetentionPolicy.RUNTIME) //描述注解的保留阶段
@Documented //描述注解是否被抽取到avaDoc api中
@Inherited //描述注解是否可以被子类继承
public @interface anno1 {
/*
属性:在揍口中定义的抽象方法
返回结果必须是如下类型
1.基本数据类型(不能是包装类型)
2.String类型
3.枚举类型
4.注解
5.以上类型的数组
如果注解中只存在一个属性且名称为value,则使用注解的时候可以省略value不写
*/
}
//反编译后
public interface anno1 extends java.lang.annotation.Annotation{
    //说明注解是一个接口继承了Annotation
}

五、注解案例

通过反射调用指定方法

//注解
@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface Anno {
    String className();
    String methodName();
}
//定义反射调用的方法
public class Student {

    public void run(){
        System.out.println("奔跑的青年...");
    }
}
//测试方法
//@Anno(className = "com.mxf.gupao.annotaion.Student",methodName = "run")
public class AnnoTest {

    @Anno(className = "com.mxf.gupao.annotaion.Student",methodName = "run")
    public static void test(){
        System.out.println("这是测试注解的方法");
    }

    public static void main(String[] args) throws Exception {
        //获取本类指定名称的注解
        Class<AnnoTest> annoTestClass = AnnoTest.class;
        //获取类上面的注解
        /*Anno annotation = annoTestClass.getAnnotation(Anno.class);
        System.out.println(annotation.className());
        System.out.println(annotation.methodName());*/
        //获取方法上的注解
        Method test = annoTestClass.getMethod("test");
        Anno annotation = test.getAnnotation(Anno.class);
        System.out.println(annotation.className());
        System.out.println(annotation.methodName());

        Class<?> aClass = Class.forName(annotation.className());
        Student s = (Student)aClass.newInstance();
        Method method = aClass.getMethod(annotation.methodName());
        method.invoke(s);
        test.invoke(null);
    }
}
/*
测试结果
com.mxf.gupao.annotaion.Student
run
奔跑的青年...
这是测试注解的方法
*/
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值