自定义注解 1

来源:互联网 发布:淘宝开店要两张银行卡 编辑:程序博客网 时间:2024/06/10 03:31

知识准备:                         元注解 (不知道就手动百度咯!)

/**
 * 自定义注解
 * @author josson
 *
 */
@Documented  
@Target({ElementType.METHOD})  
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
    public String name() ;//声明的注解属性:该field的名字,没有默认,必须填写
    public String sex() default "男";
    public boolean isValidate() default true;//声明的注解属性:是否需要校验
    public int maxLength() default 0;// 声明注解的属性:长度
    //注意:声明属性类型可以使基本类型(int,byte,short,long,float,double,boolean,)
    // 还可以是String ,Class,enum,Annotation,以上所有类型的数组
}


/**
 * 测试类
 * @author josson
 *
 */
/*@MyAnnotation(name = "王乐")*/
public class Test {
    @MyAnnotation(name = "丽丽", sex = "女")
    public void addLili() {

    }
    public static void main(String[] args) {
        Method[] methods = Test.class.getMethods();
        for (Method method : methods) {
            //检查方法中是否含使用了注解
            boolean isAnnotationPresent    =method.isAnnotationPresent(MyAnnotation.class);
            if (isAnnotationPresent) {
                String name = method.getName();
                System.out.println(name+"----"+"方法使用了注解"+"---");
                //获得注解属性:
                 MyAnnotation method2 = method.getAnnotation(MyAnnotation.class);
                System.out.println(method2.name()+"------"+method2.sex());
            }
        }
    }
}

结果:

false
addLili----方法使用了注解---
丽丽------女

注意:

1.用到注解,报如下错误,包导入不进来
    RetentionPolicy cannot be resolved to a variable
    ElementType cannot be resolved to a variable

@Retention和@Target都能导入进来,没办法只能手动导入包了
    import java.lang.annotation.*

    import java.lang.annotation.RetentionPolicy;
    import java.lang.annotation.ElementType;
这样,RetentionPolicy/ElementType cannot be resolved to a variable问题就解决了

0 0
原创粉丝点击