java怎么通过反射给成员变量添加自定义注解,请写出示例代码和测试用例,注意要用到反射哦.
1条回答 默认 最新
- 一起看海呦 2023-05-30 19:39关注
public class Test { public String name; public int age; } public class Main { public static void main(String[] args) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { // 获取Test类 Class<Test> clazz = Test.class; // 获取name字段 Field nameField = clazz.getDeclaredField("name"); // 将@MyAnnotation注解添加到name字段 nameField.setAnnotation(MyAnnotation.class.getConstructor(String.class).newInstance("name annotation")); // 获取age字段 Field ageField = clazz.getDeclaredField("age"); // 将@MyAnnotation注解添加到age字段 ageField.setAnnotation(MyAnnotation.class.getConstructor(String.class).newInstance("age annotation")); // 测试获取注解 Test test = new Test(); MyAnnotation nameAnnotation = nameField.getAnnotation(MyAnnotation.class); System.out.println(nameAnnotation.value()); // name annotation MyAnnotation ageAnnotation = ageField.getAnnotation(MyAnnotation.class); System.out.println(ageAnnotation.value()); // age annotation } } @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) @interface MyAnnotation { String value(); }
解决 无用评论 打赏 举报
悬赏问题
- ¥15 微信会员卡等级和折扣规则
- ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
- ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
- ¥15 gdf格式的脑电数据如何处理matlab
- ¥20 重新写的代码替换了之后运行hbuliderx就这样了
- ¥100 监控抖音用户作品更新可以微信公众号提醒
- ¥15 UE5 如何可以不渲染HDRIBackdrop背景
- ¥70 2048小游戏毕设项目
- ¥20 mysql架构,按照姓名分表
- ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分