获取⾃定义注解上的值
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));
}
}世界上最小的猴子
}