Java-----注解

一、注解(Annotation)

                什么是注解:

                    Annotation其实就是代码里的特殊标记, 它用于替代配置文件,也就是说,传统方式通过配置文件告诉类如何运

行,有 了注解技术后,开发人员可以通过注解告诉类如何运行。在Java技术里注解的典型应用是:可以通过反射技术去得

到类里面的注解,以决定怎么去运行类。

                三个基本注解:

    @Override://限定重写父类方法, 该注解只能用于方法

​	@Deprecated://用于表示某个程序元素(类, 方法等)已过时

​	@SuppressWarnings: //抑制编译器警告. 

                如何定义注解:

//MyAnnotation注解
public @interface MyAnnotation {
    String name();   //String类型
    int age();       //基本数据类型
    Class<String> aClass();  //Class类型
    Person PERSON();         //枚举类型
    MyChild child();    // 注解类型
    String[] arr();     //以上类型的一维数组形式
}  

//MyChild注解
public @interface MyChild {
    String child();
}

//枚举
public enum Person {
    PERSON
}

           如何使用注解:

//下面写的很繁琐,有很多种调用show方法的办法,这里主要是为了演示反射获取show方法 
public static void main(String[] args) throws Exception {
        //获取类对象
        Class<MyAnnTest> myAnnTestClass = MyAnnTest.class;
        //通过类对象创建无参的构造方法
        MyAnnTest myAnnTest = myAnnTestClass.newInstance();
        //获取方法或者参数
        Method show = myAnnTestClass.getMethod("show", new Class[]{String.class, int.class, String.class});
        //获取方法中的获取注解
        MyAnnotation annotation = show.getAnnotation(MyAnnotation.class);
        //获取值
        String name = annotation.name();
        int age = annotation.age();
        String sex = annotation.sex();
        show.invoke(myAnnTest, name,age,sex);
    }
    @MyAnnotation(name="张三",age=20,sex="男")   //给注解赋值
    public void show(String name,int age,String sex){
        System.out.println("姓名:"+name+" 年龄:"+age+" 性别:"+sex);
    }

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值