JAVA注解入门

 

package testannotation;
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;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * @Target说明了Annotation所修饰的对象范围
 * @Retention定义了该Annotation被保留的时间长短
 * @Documented用于描述其它类型的annotation应该被作为被标注的程序成员的公共API
 */

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@interface TypeAnnotation {
    String value() default "DefaultTypeAnnotation";
}

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@interface MethodAnnotation {
    String name() default "Default Annotation Name";
    String url() default "default.com";
}

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@interface FieldAnnotation {
    String value() default "DefaultFieldAnnotation";
}

@TypeAnnotation("Test the use of TypeAnnotation")
class UseAnnotion {

    @FieldAnnotation(value="FieldAnnotation with value")
    private String field;
    
    @FieldAnnotation
    private String fieldWithDefault;
    
    @MethodAnnotation()
    public void testMethodAnnotation() {
        System.out.println("UseAnnotion->testMethodAnnotation");
    }
    
    @MethodAnnotation(name="唯品会",url="vip.com")
    public void testMethodAnnotationWithValue() {
        System.out.println("UseAnnotion->testMethodAnnotationWithValue");
    }
}

public class TestAnnotation {

    public static void main(String[] args) throws ClassNotFoundException {
        Class anno = Class.forName("testannotation.UseAnnotion");
        Method[] method = anno.getMethods();

        boolean flag = anno.isAnnotationPresent(TypeAnnotation.class);
        if (flag) {
            TypeAnnotation first = (TypeAnnotation) anno.getAnnotation(TypeAnnotation.class);
            System.out.println("类型注解值:" + first.value());
        }

        for (Method m : method) {
            MethodAnnotation methodAnno = m
                    .getAnnotation(MethodAnnotation.class);
            if (methodAnno == null)
                continue;

            System.out.println("获取方法注解\nname:\t"
                    + methodAnno.name() + "\nurl:\t" + methodAnno.url());
        }
        Field []field = anno.getDeclaredFields();
        for(Field f : field) {
            FieldAnnotation fieldAnnotation = (FieldAnnotation)f.getAnnotation(FieldAnnotation.class);
            System.out.println("获取域注解:"+fieldAnnotation.value());
        }
    }
}

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。