自定义注解并取值
定义注解
@Target(ElementType.FIELD) //注解用于字段上
@Retention(RetentionPolicy.RUNTIME) //注解用于运行时
public @interface MyField {
String description();
int length();
}
测试
public class TestOne {
@MyField(description = "这个是自己的注解", length = 3)
private static String name;
public static void main(String[] args) {
Class t = TestOne.class;
Field[] declaredFields = t.getDeclaredFields();
for (Field declaredField : declaredFields) {
if (declaredField.isAnnotationPresent(MyField.class)) {
String description = declaredField.getAnnotation(MyField.class).description();
int length = declaredField.getAnnotation(MyField.class).length();
System.out.println(description);
System.out.println(length);
}
}
}
}
还没有评论,来说两句吧...