类型注解使用
package com.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.ArrayList;
import java.util.List;
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE_PARAMETER, ElementType.TYPE_USE})
@interface Annot{
}
class Person<@Annot T> {
@SuppressWarnings("unused")
public @Annot T method(@Annot T num) {
int xx = (@Annot int)50L;
List<@Annot T> l = new ArrayList<>();
return num;
}
}
public class AnnotationTest2 {
}
自定义注解类
package com.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
@Documented
@Repeatable(MyAnnotations.class)
@interface MyAnnotation {
String value();
}
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
@interface MyAnnotations {
MyAnnotation[] value();
}
@MyAnnotation("jock")
@MyAnnotation("xxx")
public class AnnotationTest {
public static void main(String[] args) {
AnnotationTest at = new AnnotationTest();
MyAnnotations annotation = at.getClass().getAnnotation(MyAnnotations.class);
MyAnnotation[] v = annotation.value();
for(MyAnnotation a : v) {
System.out.println(a.value());
}
}
}