Java 注解处理器

       Java从JDK1.5开始加入“注解”这一功能,目的是为了对抗以C#为首的一批类Java语言,这里简要介绍一下Java注解的使用以及定义等操作。

1.定义一个注解:

package myannotation;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Retention(RetentionPolicy.RUNTIME)
public @interface A {

    public int id() default 0;

    public String value() default "default";

}

2.定义一个使用了该注解的类:

package myannotation;

@A
public class C {

    @A("age")
    public int age;

    @A(id = 10, value = "welcome")
    public void hello(){}

}
3.通过Java的反射机制来实现「注解处理器」:

package myannotation;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class Test {

    public static void main(String[] args){

        if(C.class.isAnnotationPresent(A.class)){
            A a = (A)C.class.getAnnotation(A.class);
            System.out.printf("Class: id = %s, value = %s\n", a.id(), a.value());
        }

        Field[] fields = C.class.getFields();
        for (Field field : fields){
            if(field.isAnnotationPresent(A.class)){
                A a = (A)field.getAnnotation(A.class);
                System.out.printf("Field: id = %s, value = %s\n", a.id(), a.value());
            }
        }

        Method[] methods = C.class.getMethods();
        for (Method method : methods){
            if(method.isAnnotationPresent(A.class)){
                A a = (A)method.getAnnotation(A.class);
                System.out.printf("Method: id = %s, value = %s\n", a.id(), a.value());
            }
        }

    }

}
上面这个类的运行结果为:

Class: id = 0, value = default
Field: id = 0, value = age
Method: id = 10, value = welcome

结果符合我们在类中对注解所赋予的值。


太晚了,先写到这里,有时间再写。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值