【Java SE】Annotation

2017-04-13  本文已影响20人  KingJA

1# Annotation

Provides library support for the Java programming language annotation facility.

2# Key Class

2.1# java.lang

2.2# java.lang.Annotation | Annotation Types

2.2# java.lang.Annotation | Enum

3# Common Annotation Class

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Target {
    ElementType[] value();
}
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Retention {
    RetentionPolicy value();
}
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Documented {
}

4# Annotation Elements Returns

5# Custom Annotation

5.1# Annotation Class

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Robot {
    public enum RobotSize {BIG, MED, MIN;}
    int robotcount() default 1;
    String robotName() default "ET";
    RobotSize robotSize() default RobotSize.MED;
}

5.2# applied to a method

@Robot(robotcount = 5, robotName = "XMAN", robotSize = Robot.RobotSize.BIG)
    public void buildRobot() {}

5.3# get the annotation info by reflection

public class RobotBuilder {
    public static void main(String[] args) {
        getAnnotationInfo(RobotBuilder.class);
    }

    private static void getAnnotationInfo(Class<RobotBuilder> robotBuilderClass) {
        Method[] methods = robotBuilderClass.getDeclaredMethods();
        for (Method method : methods) {
            Robot annotation = method.getAnnotation(Robot.class);
            if (annotation != null) {
                int robotcount = annotation.robotcount();
                String robotName = annotation.robotName();
                Robot.RobotSize robotSize = annotation.robotSize();
                System.out.println(">>>robotcount:"+robotcount);
                System.out.println(">>>robotName:"+robotName);
                System.out.println(">>>robotSize:"+robotSize);
            }
        }
    }

    @Robot(robotcount = 5, robotName = "XMAN", robotSize = Robot.RobotSize.BIG)
    public void buildRobot() {}
}

output

>>>robotcount:5
>>>robotName:XMAN
>>>robotSize:BIG
上一篇下一篇

猜你喜欢

热点阅读