码迷,mamicode.com
首页 > 编程语言 > 详细

JAVA注解入门

时间:2015-01-28 00:41:58      阅读:176      评论:0      收藏:0      [点我收藏+]

标签:

 

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

 

JAVA注解入门

标签:

原文地址:http://www.cnblogs.com/hellocyc/p/4254663.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!