“注解“的定义,使用和解析

//注解的定义
 

//@Target,修饰所有能够修饰的东西
@Target({ElementType.TYPE,ElementType.METHOD,ElementType.FIELD})
//如果设置存活时间,默认只存活在原码阶段---->字节码  ---->运行期间
@Retention(RetentionPolicy.RUNTIME)
//定义注解
public @interface Anno {
    int value();
    int [] method();
    String method1();
}

//使用注解
 

@Anno(value = 56 , method = 23,method1 = "我爱你")

public class Person {
    @Anno(value = 66,method = 88,method1 = "真是一个阳光明媚的一天")
private String name ;
private int age;


    public Person() {
    }

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
    @Anno(value = 23,method = 34,method1 = "你看看哥哥够不够帅")
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
 


 //解析注解

publiclass Test {
    public static void main(String[] args) throws NoSuchFieldException, NoSuchMethodException {
        //获取字节码文件
        Class<Person> personClass = Person.class;
        //类的注解解析
        Anno annotation = personClass.getAnnotation(Anno.class);
        int[] method = annotation.method();
        String s = annotation.method1();
        int value = annotation.value();
        System.out.println(Arrays.toString(method));
        System.out.println(s);
        System.out.println(value);
        //成员变量的注解解析
        Field name = personClass.getDeclaredField("name");
        Anno annotation1 = name.getAnnotation(Anno.class);
        int[] method1 = annotation1.method();
        String s1 = annotation1.method1();
        int value1 = annotation1.value();
        System.out.println(Arrays.toString(method1));
        System.out.println(s1);
        System.out.println(value1);
        //成员方法的注解解析
        Method getName = personClass.getDeclaredMethod("getName");
        Anno annotation2 = getName.getAnnotation(Anno.class);
        int[] method2 = annotation2.method();
        String s2 = annotation2.method1();
        int value2 = annotation2.value();
        System.out.println(Arrays.toString(method2));
        System.out.println(s2);
        System.out.println(value2);

    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值