获取自定义注解上的值

更新时间:2023-07-15 13:30:20 阅读: 评论:0

获取⾃定义注解上的值
package ⾃定义注解;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface AnnotationTest {
String age() default "20";
String name() default "fz";
}
package ⾃定义注解;
public class Person {
@AnnotationTest(name = "fg")
南果梨private String name;
@AnnotationTest(age="24")
private String age;
}
内存条型号怎么看package ⾃定义注解;
import java.lang.annotation.Annotation;
十回向import flect.AnnotatedType;
二苯胺import flect.Field;
/*
* 1.⾸先获取优质定义注解修饰类的类对象,根据类对象获取对应的属性。
光的折射和反射* 2.判断属性上是否有注解修饰,有就获取对应的注解。(通过属性获取对应的注解,获取属性上的值就⽤属性去Annotation(AnnotationTest.class);)
* 3.为属性赋值。第⼀步中的属性赋值为注解中获取的属性值。
*
* */
public class Test {党支部鉴定意见
public static void main(String[] args) throws Exception {
Class p=Person.class;
Field declaredField = p.getDeclaredField("name");
declaredField.tAccessible(true);千佛洞
if(declaredField.isAnnotationPrent(AnnotationTest.class)) {
AnnotationTest annotation = Annotation(AnnotationTest.class);
//System.out.println(annotation.age()+":"+annotation.name());
String name = annotation.name();
Person p1=new Person();
declaredField.t(p1, name);//为declaredfield属性赋name值,其中name必须是p1中的属性。所以需要p1对象            System.out.(p1));
}
}世界上最小的猴子
}

本文发布于:2023-07-15 13:30:20,感谢您对本站的认可!

本文链接:https://www.wtabcd.cn/fanwen/fan/82/1097939.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:注解   获取   属性   型号
相关文章
留言与评论(共有 0 条评论)
   
验证码:
推荐文章
排行榜
Copyright ©2019-2022 Comsenz Inc.Powered by © 专利检索| 网站地图