反射获取注解信息
ORM:Object relationship Mapping(对象关系映射):类和数据库表相对应
后期框架的基本原理就是反射获取注解中的信息
package com.li.changGe.reflection.runtimeStructure;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Field;
@MyAnnotation(name = "张三",age = 19,sex = '男')
public class AnnotationDemo01 {
@MyAnnotation(name = "长歌",age = 20,sex = '女')
private static String names;
public static void main(String[] args) throws NoSuchFieldException {
/**
* 获取类上的注解信息
*/
Class<AnnotationDemo01> annotationDemo01Class = AnnotationDemo01.class;
MyAnnotation annotation = annotationDemo01Class.getAnnotation(MyAnnotation.class);
String name = annotation.name();
/**
* 获取字段上的注解信息
*/
Field field = annotationDemo01Class.getDeclaredField("names");
MyAnnotation annotation1 = field.getAnnotation(MyAnnotation.class);
int age = annotation1.age();
/**
* 张三
* 20
*/
System.out.println(name+"\n"+age);
/**
* 为字段赋值要标明是给哪个对象的字段赋值
*/
field.set(annotationDemo01Class,"王五");
System.out.println(names);//王五
}
}
//自定义注解
@Target({ElementType.TYPE,ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation{
String name();
int age();
char sex();
}