Java注解笔记

不详细说明,个人学习的笔记
只列出代码 和 注释


自定义注解

package top.demo.test;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

//@Target
//@Retention
//@Documented
//@Inherited

//规定该注解在什么地方能用
@Target(value= {ElementType.METHOD,ElementType.TYPE})
//规定注解在什么时候能用  runtime 是在程序运行期间都能用,通过反射可得到信息
@Retention(value=RetentionPolicy.RUNTIME)
public @interface MyAnnotation {

    //注解在大括弧里 不是函数代码 实际上上注解的参数
    //类型 名称 默认值
    String test() default "";
    int age() default 18;
    int id();
    String[] arry() default {"1","2"};
    String[] arry2();


}

定义测试类

package top.demo.test;

@MyAnnotation(id=88,arry2= {"99"})
public class Test {

    @MyAnnotation(id=999,arry2= {"888"})
    public static void test1()
    {
        System.out.println("this is annotation test");
    }

}

定义 注解处理类

    package top.demo.test;

    import java.lang.reflect.*;
    import java.lang.annotation.Annotation;

    public class Action {

        public static void main(String argv[]) throws ClassNotFoundException, NoSuchMethodException, SecurityException {

            Class cl=Class.forName("top.demo.test.Test");

            MyAnnotation an=(MyAnnotation) cl.getAnnotation(MyAnnotation.class);
            System.out.println(an.id());

            Method test1=cl.getMethod("test1", null);

            an=test1.getAnnotation(MyAnnotation.class);
            System.out.println(an.id());


        }

    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值