java自定义注解实例

来源:互联网 发布:淘宝直通车删除计划 编辑:程序博客网 时间:2024/06/04 18:17

java自定义注解实例

@(Java)
通过前两篇文章,初步了解了java的注解后,在这一篇中,将实现自己的自定义注解。
前两篇文章详细见:
java元注解及源码浅析
java内建注解及源码浅析

为什么要使用自定义注解?

刚开始接触到注解的时候,我一直有个疑问,就是我们为什么要使用注解?随着对注解的逐渐了解,慢慢的感受到了注解的强大功能。在程序运行过程中,通过对注解的解释,可以决定程序的执行顺序。而且自定义注解并不会影响程序的逻辑,仅起到辅助性作用。

引用:举个例子,在Jersey webservice中,我们在一个方法上添加了PATH注解和URI字符串,在运行期,jersey会对其进行解析,并决定作用于指定URI模式的方法。

实例

首先看下程序的结构图,比较简单:
Alt text
一个主程序Main,一个交通工具接口,两个实现类,和一个Annotation。

AnnotationVehicle
@Documented@Target({ElementType.FIELD,ElementType.METHOD})@Retention(RetentionPolicy.RUNTIME)public @interface AnnotationVehicle {    //交通工具名称    String name() default "";    //交通工具描述    String desc() default "";}
IVehicle
//定义交通工具接口public interface IVehicle {    void test() ;}
Car
public class Car implements IVehicle{    //作为自定义annotaiton参数的例子    @AnnotationVehicle(name = "Car")    private String name ;    //作为自定义annotaiton方法的例子    @Override    @AnnotationVehicle(desc = "run")    public void test() {        // TODO Auto-generated method stub    }}
Plane
public class Plane implements IVehicle{    //作为自定义annotaiton参数的例子    @AnnotationVehicle(name = "Plane")    private String name ;    //作为自定义annotaiton方法的例子    @Override    @AnnotationVehicle(desc = "fly")    public void test() {        // TODO Auto-generated method stub    }}
主类Main
public class Main {    public static void main(String[] args) {        getVehicleInfo(new Car());        getVehicleInfo(new Plane());    }    //为代码清晰,将filed与method的获取方法分开    public static void getVehicleInfo(IVehicle vehicle){        filedInfo(vehicle.getClass());        methodInfo(vehicle.getClass(), vehicle);    }    //解析annotation的field    public static void filedInfo(Class<?> cls){        Field[] fields = cls.getDeclaredFields();        for (Field field : fields) {            if (field.isAnnotationPresent(AnnotationVehicle.class)) {                AnnotationVehicle annotationVehicle = field                        .getAnnotation(AnnotationVehicle.class);                System.out.println("This is :" + annotationVehicle.name());            }        }    }    //解析annotation的method    public static void methodInfo(Class<?> cls,IVehicle vehicle){        Method[] methods = cls.getMethods();        for (Method method : methods) {            if (method.isAnnotationPresent(AnnotationVehicle.class)) {                AnnotationVehicle annotationVehicle = method                        .getAnnotation(AnnotationVehicle.class);                System.out.println(annotationVehicle.desc());            }        }    }}
运行结果

This is :Car
run
This is :Plane
fly

总结

通过上面一个简单的小例子,可以初步的运用自定义的annotation。但annotation的功能远非如此。通过解析annotation获取的值来判断要走哪些业务逻辑等用法,使java编程更加的灵活。

参考:

http://www.importnew.com/14479.html
http://blog.csdn.net/bao19901210/article/details/17201173/

0 0