209.自定义注解

package com.bjsxt.test.annotation;

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

@Target(value={ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface SxtAnnotation01 {
    
    String studentName() default "";
    int age() default 0;
    int id() default -1;   //String indexOf("abc")  -1
    
    String[] schools() default {"清华大学","北京上学堂"};
    
}

注解1 

SxtAnnotation01 范围是可以使用在类的方法
ElementType.METHOD以及对类做注解
ElementType.TYPE
注解运行的有效期是:
@Retention(RetentionPolicy.RUNTIME)
定义可三个字段
studentName、age id,已经schools,每个字段都使用了一个默认值
package com.bjsxt.test.annotation;

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

@Target(value={ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface SxtAnnotation02 {
    String value();
}
有了上面的注解,现在我们这样使用注解了
 
package com.bjsxt.test.annotation;


/**
 * 测试自定义注解的使用
 *
 */
@SxtAnnotation01
public class Demo02 {
    
    @SxtAnnotation01(age=19,studentName="老高",id=1001,
            schools={"北京大学","北京航空航天大学"})
    public void test(){
    }
    
    @SxtAnnotation02("aaaa")
    public void test2(){
    }
    
}
这里对应注解  @SxtAnnotation02("aaaa"),为啥能这样写而不是写成  @SxtAnnotation02(value="aaaa"),这里因为SxtAnnotation02中只有一个成员变量value,所以我们就可以这样写


原文地址:https://www.cnblogs.com/kebibuluan/p/7268099.html