think in java - annotation

# what's annotation, why we need annotation?

- metadata

- to combine metadata with source code files.

- help to ease the burden of writing boilerplate code.


# define annotation

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Test {}

@Target : define where you can apply this annotation.

@Retention: defines where the annotation is available in source code, in class files or at the runtime.

- above one has no elements, so it's a marker annotation.


# simple annotation

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface UseCase {
    // id is type-checked by complier
    public int id();
    public String description() default "no description";
}


# annotation processor

public class UseCaseTracker {
    public static void main(String[] args) {
        List<Integer> useCases = new ArrayList<Integer>();
        Collections.addAll(useCases, 47, 48, 49, 50);
        trackUseCases(useCases, PasswordUtils.class);
    }

    private static void trackUseCases(List<Integer> useCases, Class cl) {
        for (Method method : cl.getDeclaredMethods()) {
            UseCase uc = method.getAnnotation(UseCase.class);
                if (null != uc) {
                    System.out.println("Found use case: " + uc.id() + ", " + uc.description());
                    useCases.remove(new Integer(uc.id()));
                }
        }
        for (int i : useCases) {
            System.out.println("warning: missing use case: " + i);
        }
    }
}


# what types of element are allowed in annotation?

- all primitive.

- String

- Class

- enum

- annotation

- 1-dimention array of any of the above.


# what's the restriction using annotation?

- no element can have an unspecified value, all elements must either have default values or values provided by the class that uses the annotation.



转载于:https://my.oschina.net/u/1242229/blog/287331

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值