Java基础教程
作者: 时海
自定义Annotation

使用自定义注解设置JavaBean对象的属性,示例如下:

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

public class Test {
    //定义bean
    static class Cat {
        private String name;

        private int age;

        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;
        }

    }

    //自定义注解
    @Retention(RetentionPolicy.RUNTIME)
    static @interface CatAnnotation {
        String name();

        int age();
    }

    //处理类
    static class Handler {
        Cat cat;

        public Cat getCat() {
            return cat;
        }

        //使用注解设置JavaBean属性
        @CatAnnotation(name = "kitty", age = 3)
        public void setCat(Cat cat) {
            this.cat = cat;
        }

        public void print() {
            System.out.println("name:" + cat.getName() + ",age:" + cat.getAge());
        }

    }

    public static void main(String[] args) throws Exception {

        Handler handler = new Handler();

        //获取注解值
        Method method = Handler.class.getMethod("setCat", Cat.class);
        CatAnnotation annotation = method.getAnnotation(CatAnnotation.class);

        //注入
        Cat cat = new Cat();
        cat.setName(annotation.name());
        cat.setAge(annotation.age());
        
        handler.setCat(cat);
        handler.print();

    }
}


标签: cat、age、handler、annotation、catannotation
一个创业中的苦逼程序员
  • 回复
隐藏