javaSE(26)(注解)

来源:互联网 发布:js removechild all 编辑:程序博客网 时间:2024/06/17 11:56
1.package com.vince.annotation;//使用自定义注解@MyAnnotation(name="XB",like={"泡妞","睡觉"},sex=EnumSex.GG)public class User {    private String name;    public User(String name){        this.name = name;    }    public String getName() {        return name;    }    public void setName(@MyAnnotation(name="XB",like={"泡妞","睡觉"},sex=EnumSex.GG) String name) {        this.name = name;    }    @Override    public String toString() {        return "my name is "+name;    }    @Deprecated    public void print(){        System.out.println("name="+name);    }}2.package com.vince.annotation;import java.lang.annotation.Documented;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;/** * 自定义一个注解 * @author lamp * */@Documented@Target({ElementType.TYPE,ElementType.METHOD,ElementType.PARAMETER})@Retention(value=RetentionPolicy.RUNTIME)//元注解//元数据public @interface MyAnnotation {    public String name();//定义一个属性    //定义一个属性,并指定默认值    public String info() default "WSDR";    public String[] like();//定义一个数组变量    public EnumSex sex();//定义一枚举变量}3.package com.vince.annotation;import java.lang.annotation.Annotation;public class AnnotationDemo {    /**     * @param args     * @throws Exception      */    @SuppressWarnings("deprecation")    public static void main(String[] args) throws Exception {        User user = new User("XB");        user.print();        //使用反射解析注解        Class<?> c = Class.forName("com.vince.annotation.User");        //获取当前类标记的所有注解        Annotation[] annotations = c.getAnnotations();        System.out.println(annotations.length);        for (Annotation a : annotations) {            //判断是否是指定的注解            if(c.isAnnotationPresent(MyAnnotation.class)){                MyAnnotation ma = (MyAnnotation)a;                String name = ma.name();                System.out.println(name);            }        }    }}4.package com.vince.annotation;public enum EnumSex {    MM,GG}
0 0
原创粉丝点击