注解
作用
用作于注释
可以被程序读取
元注解
处理注解的注解,一共有四个
@Target(value = ElementType.TYPE)
@Retention(value = RetentionPolicy.RUNTIME)
@Documented
@Inherited
@interface MyAnnotation {
//参数定义 类型 + 参数名 + () 只有一个参数,并且参数名叫value时,使用者可以省略参数名传值
String value();
}
自定义注解的使用
public class Client2 {
public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException {
Class studentClass = Class.forName("Student");
ClassAnnotation classAnnotation = (ClassAnnotation) studentClass.getAnnotation(ClassAnnotation.class);
System.out.println(classAnnotation.db_name());
<pre><code> Field fieldage = studentClass.getDeclaredField("age");
FieldAnnotation fieldAnnotation = (FieldAnnotation) fieldage.getAnnotation(FieldAnnotation.class);
System.out.println(fieldAnnotation.name() + "," + fieldAnnotation.length() + "," + fieldAnnotation.size());
}
}
@ClassAnnotation(db_name = "Stu") class Student { @FieldAnnotation(name = "cjj", length = 5, size = 9) private int age; private String name; }
@Target(value = {ElementType.TYPE}) @Retention(value = RetentionPolicy.RUNTIME) @interface ClassAnnotation { String db_name(); }
@Target(value = {ElementType.FIELD}) @Retention(value = RetentionPolicy.RUNTIME) @interface FieldAnnotation { String name();
int length();
int size();
}
评论区