java注解

一、注解定义:

 //表示该注解可作用于方法、类和接口、局部变量上,构造函数上
@Target({ElementType.METHOD,ElementType.TYPE,ElementType.LOCAL_VARIABLE,ElementType.CONSTRUCTOR})
//表示在运行时有效
@Retention(RetentionPolicy.RUNTIME) 
//注解允许继承
@Inherited 
//表示在文档中生成
@Documented 
public @interface Custom {

    String desc();
    String author();
    int age(); 
}

注意:
1.当注解只有一个成员时,则成员名必须取名为valuse(),使用时可以忽略成员名和赋值号=
2.成员类型是受限的,合法的类型包括基本数据类型(char、int、double、float等等,不包括:Character、Interger、Double、Long等)和String 、Class、Annotation、Enumeration。
3.注解可以没有成员,没有成员的注解成为标识注解
4.注解成员必须是无参无异常

二、解析注解:

public static void parseAnnotation(Class<?> clazz){
        try {

            //判断类或接口上是否有注解
            boolean isAnnotationClass = clazz.isAnnotationPresent(Custom.class);
            if(isAnnotationClass){
                Custom custom = clazz.getAnnotation(Custom.class);
                System.out.println(custom.desc() + custom.master() + custom.age());
            }
            //方法一:
            //获取dogClass这个类中所有的方法
            Method[] methods = clazz.getMethods();
            for(Method method: methods){
                //判断方法上是否有Custom注解
                boolean isAnnotationMethod = method.isAnnotationPresent(Custom.class);
                if(isAnnotationMethod){
                    Custom annotation = method.getAnnotation(Custom.class);
                    System.out.println(annotation.desc() + annotation.master() + annotation.age());

                }
            }
            //方法二:
            for(Method method :methods){
                Annotation[] annotations = method.getAnnotations(); //获取这个方法上的所有注解
                for(Annotation annotation : annotations){
                    if(annotation instanceof Custom){
                        System.out.println(((Custom) annotation).desc() + ((Custom) annotation).master() + ((Custom) annotation).age());
                    }
                }
            }

        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

另:getMethods()和getDeclaredMethods()区别
public Method[] getMethods()返回某个类的所有公用(public)方法包括其继承类的公用方法,当然也包括它所实现接口的方法。
public Method[] getDeclaredMethods()对象表示的类或接口声明的所有方法,包括公共、保护、默认(包)访问和私有方法,但不包括继承的方法。当然也包括它所实现接口的方法。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

楚蕊博南谭

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值