使用反射获取注解中的内容

时间:2022-07-28
本文章向大家介绍使用反射获取注解中的内容,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

首先,需要有一个注解

@Target({ElementType.TYPE, ElementType.FIELD, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
    String FilePath();
}

其中:

@Target({ElementType.TYPE, ElementType.FIELD, ElementType.METHOD})
TYPE: 当前注解可以用于类声明 、
FIELD:当前注解可以用于成员变量声明位置、
METHOD: 当前注解可以用于方法声明位置 。

@Retention(RetentionPolicy.RUNTIME)
当前注解参与代码运行

然后,需要有个.java文件

@MyAnnotation(FilePath = "F:\test\day25\StudentSystemV1.4\data\students.json")
public class DataUtils {
	//文件路径
	private static String str;
	//通过注解,得到文件路径
	public static void main(String[] args) {
		
		Class<DataUtils> cls = DataUtils.class;
		MyAnnotation annotation = cls.getAnnotation(MyAnnotation.class);

		str = annotation.FilePath();
		System.out.println(str);
	}
}

输出结果

F:testday25StudentSystemV1.4datastudents.json

Process finished with exit code 0