package com.chixing.day16.annotation;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class ParseAnnotation {
public static void main(String[] args) {
//获得AnnotationDemo中的字段与注解的详细信息
//1.类加载
Class<AnnotationDemo> clazz = com.chixing.day16.annotation.AnnotationDemo.class;
//2.获取字段
Field[] field = clazz.getDeclaredFields();
for (Field f : field) {
//字段名
String fName = f.getName();
//字段权限
int fModifiers = f.getModifiers();
//字段类型
Class fType = f.getType();
System.out.println("字段名:" + fName + " 字段权限:" + fModifiers + " 字段类型:" + fType);
//获取字段的注解
Annotation[] annotations = f.getDeclaredAnnotations();
for (Annotation a : annotations) {
System.out.println(f.getName()+"字段上有注释:"+a);
}
}
//获取方法
Method[] method = clazz.getDeclaredMethods();
for (Method m : method){
//获取注解
Annotation[] annotations = m.getDeclaredAnnotations();
for (Annotation a : annotations){
System.out.println(m.getName()+"方法上有注释:"+a);
}
}
}
}
注解的内容
package com.chixing.day16.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.METHOD,ElementType.FIELD})//注解的作用范围
@Retention(RetentionPolicy.RUNTIME)//注解的作用时长,运行时保留
public @interface Mymessage {
String name() default "sam";
int num() default 0;
String desc();
}
示例
package com.chixing.day16.annotation;
public class AnnotationDemo {
@Mymessage(num = 10,name = "a",desc = "静态变量a")
private static int a = 10;
@Mymessage(name = "add",desc = "类中的一个普通方法")
public void add(){
}
}