编程语言
首页 > 编程语言> > java注解

java注解

作者:互联网

注解类MyAnno.java
@Inherited//子类可以继承父类
@Documented//注解将包含在javadoc中
@Retention(RetentionPolicy.RUNTIME )
@Target(value = {ElementType.METHOD,ElementType.TYPE})
public @interface MyAnno {
    //注解的参数--->参数类型+参数名()
        String value();
        int age() default 1;
        int id() default 1;
}
实验类Anno.java
public class Anno {
    @MyAnno(value = "jack",age = 18,id=10001)
    public void info(String name,int age,int id){
        System.out.println("姓名:"+name+"_年龄:"+age+"_身份:"+id);
    }
}
测试类TestAnno.java
public class TestAnno {
        public static void main(String[] args) throws Exception {
            //获取类对象
            Class<?> aClass = Class.forName("com.annotation.Anno");
            //获取类中方法
            Method info= aClass.getMethod("info", String.class, int.class, int.class);
            //获取注解
            MyAnno myAnno = info.getAnnotation(MyAnno.class);
            System.out.println(myAnno.value());
            System.out.println(myAnno.age());
            System.out.println(myAnno.id());
            Anno anno = (Anno) aClass.newInstance();
            info.invoke(anno,myAnno.value(),myAnno.age(),myAnno.id());
        }
}

输出

jack
18
10001
姓名:jack_年龄:18_身份:10001

标签:java,int,age,value,id,myAnno,注解,class
来源: https://www.cnblogs.com/netu/p/13796328.html