注解和反射

注解 Annotation

Annotation的格式:

已@注释名在代码中存在的,还可以添加一些参数值

Annotation可以附加在package,class,method,field等上面,相当于给他们添加了额外的辅助信息,我们可以通过反射机制编程实现对这些元数据的访问

内置注解

@Override:定义在java.lang.Override中,此注释只适用于修辞方法,表示一个方法声明打算重写超类中的另一个方法声明。

@Deprecated:定义在java.lang.Deprecated中,此注释可用于修辞方法,属性,类,表示不鼓励程序员使用这样的元素,通常是用为他很危险或者存在更好的选择。

@SuppressWarnings:定义在java.lang.SppressWarnings中,用来抑制编译时的警告信息。

  • 与前两个注释有所不同,你需要添加一个参数才能正确使用,这些参数都已经定义好了的,我们选择性的使用就好了。

@SuppressWarning(“all”)

@SuppressWarning(“unchecked”)

@SuppressWarning(value={“unchecked”,”deprecation”})

元注解

元注解就是负责注解其他的注解,Java定义了4个标准的meta-annootation类型,它们被用来提供对其他annotation类型作说明

这些类型和它们所支持的类在Java.lang.annotation包中可以找到.(@Target,@Retention,@Documented,@Inherited)

  • @Target:用于描述注解的使用范围
  • @Retention:表示需要在什么级别保存该注释的消息,用于描述注解的生命周期(SOURCE < CLASS < RUNTIME)
  • @Document:说明该注解将包含在javadoc中
  • @Inherited:说明子类可以继承父类中的该注解
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package annotation;

import java.lang.annotation.*;

public class Test01 {

}

// Target 表示注解可以用到那些地方
@Target(value = {ElementType.METHOD,ElementType.TYPE})

// Retention 表示注解在什么地方还有效
// runtime > class > sources
@Retention(value = RetentionPolicy.RUNTIME)

// Documented 表示是否将我们注释生成在Javadoc中
@Documented

// Inherited 子类可以继承父类的注解
@Inherited
@interface MyAnnotation{

}

自定义注解

使用@interface自定义注解时,自动继承了java.lang,annotation.Annotation接口

  • @interface用来声明一个注解,格式:public @Interface 注解名 {定义内容}
  • 其中的每个方法实际上是声明一个配置参数
  • 方法的名称就是参数的名称
  • 返回值类型就是参数的类型(返回值只能是基本类型,Class,String,enum)
  • 可以通过default来声明参数的默认值
  • 如果只有一个参数成员,一般参数名为value
  • 注解元素必须要有值,我们定义注解元素时,经常使用空字符串,0作为默认值
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

public class Test02 {
   // 注解可以显示赋值,如果没有默认值 ,必须赋值
   @MyAnnotation2(name = "xxx")
   public void test() {
  }

   @MyAnnotation3("xx")
   public void test2() {
  }
}

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation2 {
   // 注解的参数:参数类型 + 参数名();
   String name() default "";

   int age() default 0;

   int id() default -1; // 如果默认值为-1,就表示不存在

   String[] schools() default {"xxx大学", ""};

}

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation3 {
   String value();
}

反射机制

Java-Reflection

Reflection(反射)是Java被视为动态语言的关键,反射机制允许程序在程序执行期借助于Reflection API取得任何类的内部信息,并能直接操作任意对象的内部属性及方法

1
Class c = Class.forName("java.lang.String")

加载完类之后,在堆内存的方法区中就产生了一个Class类型的对象(一个类只有一个Class对象),这个对象就包含了完整的类的结构信息。我们可以通过这个对象看到类的结构。这个对象就像一面镜子,透过镜子看到类的结构,所以我们形象的称之为:反射

正常方式:*引入需要的“包类”名称* —-> *通过new实例化* —-> *取得实例化对象*

反射方式:*实例化对象* —-> ***getClass()方***法 —-> *得到完整的“包类”名称*

Java反射机制提供的功能

  • 在运行时判断任意一个对象所属的类
  • 在运行时构造任意一个类的对象
  • 在运行时判断任意一个类所具有的成员变量和方法
  • 在运行时获取泛型信息
  • 在运行时调用任意一个对象的成员变量和方法
  • 在运行时处理注解
  • 生成动态代理

反射 相关的主要API

  • java.lang.Class:代表一个类
  • java.lang.refrect.Method:代表一个类的方法
  • java.lang.refrect.Field:代表一个类的成员变量
  • java.lang.refrect.Constructor:代表一个类的构造器

Class类

在Object类中定义了一下的方法,此方法将被所有子类继承

1
public final Class getClass()

对象照镜子后可以得到的信息:某个类的属性、方法和构造器、某个类到底实现了哪些接口。对于每个类而言,JRE都是为其保留一个不变的Class类型的对象。一个Class对象包含了特定某个结构(class/interface/enum/annotation/primitive type/void/[])的有关信息。

  • Class本身也是一个类
  • Class对象只能由系统建立对象
  • 一个加载的类在JVM中只会有一个Class实例
  • 一个Class对象那个对应的是一个加载到JVM中的一个.class文件
  • 每个类的实例都会记得自己是由哪个Class实例所生成
  • 通过CLass可以完整地得到一个类中的所有被加载的结构
  • Class类是Reflection的根源,针对任何你想动态加载、运行的类,唯有先获得相应的Class对象
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package reflection;

// 什么叫反射
public class Test01 {
   public static void main(String[] args) throws ClassNotFoundException {
       // 通过反射获取类的Class对象
       Class<?> c1 = Class.forName("reflection.User");
       System.out.println(c1);

       // 一个类在内存中只有一个class对象
       // 一个类被加载后,类的整个结构都会被封装在class对象中
       System.out.println(c1.hashCode());
  }
}

// 实体类:POJO,entity
class User {
   private String name;
   private int id;
   private int age;

   public User() {
  }

   public User(String name, int id, int age) {
       this.name = name;
       this.id = id;
       this.age = age;
  }

   public String getName() {
       return name;
  }

   public void setName(String name) {
       this.name = name;
  }

   public int getId() {
       return id;
  }

   public void setId(int id) {
       this.id = id;
  }

   public int getAge() {
       return age;
  }

   public void setAge(int age) {
       this.age = age;
  }

   @Override
   public String toString() {
       return "user{" +
               "name='" + name + '\'' +
               ", id=" + id +
               ", age=" + age +
               '}';
  }
}

Class类常用的方法

方法名 功能说明
static ClassforName(String name) 返回指定类名name的Class对象
Object newInstance() 调用缺省构造函数,返回Class对象的一个实例
getName() 返回此CLass对象所表示的实体(类,接口,数组类或者void)的名称
Class getSuperClass() 返回当前Class对象的父类的Class独享
Class[] getinterfaces() 获取当前Class对象的接口
ClassLoader getClassLoader() 返回该类的类加载器
Constructor[] getConstructors() 返回一个包含某些Constructor对象的数组
Method getMothed(String name,Class… T) 返回一个Method对象,此对象的形参类型为paramType
Field[] getDeclaredFields() 返回Field对象的一个数组
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package reflection;

public class Test02 {
   public static void main(String[] args) throws ClassNotFoundException {
       Person person = new Student();
       System.out.println("这个人是:" + person.name);

       // 方式一:通过对象获得
       Class c1 = person.getClass();
       System.out.println(c1.hashCode());

       // 方式二:forName获得
       Class c2 = Class.forName("reflection.Student");
       System.out.println(c2.hashCode());

       // 方式三:通过类名.class获得
       Class c3 = Student.class;
       System.out.println(c3.hashCode());

       // 方式四:基本内置类型的包装类都有一个Type属性
       Class c4 = Integer.TYPE;
       System.out.println(c4.hashCode());

       // 获得父类类型
       Class s1 = c1.getSuperclass();
       System.out.println(s1);

  }

}

class Person {
   public String name;

   public Person() {
  }

   public Person(String name) {
       this.name = name;
  }

   @Override
   public String toString() {
       return "Person{" +
               "name='" + name + '\'' +
               '}';
  }

   public String getName() {
       return name;
  }

   public void setName(String name) {
       this.name = name;
  }
}

class Student extends Person {
   public Student() {
       this.name = "学生";
  }
}

class Teacher extends Person {
   public Teacher() {
       this.name = "老师";
  }
}

哪些类型可以有Class对象

  • class:外部类,成员(成员内部类,静态内部类),局部内部类,匿名内部类
  • interface:接口
  • []:数组
  • enum:枚举
  • annotation:注解@interface
  • primitive type:基本数据类型
  • void
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package reflection;

import java.lang.annotation.ElementType;

// 所有类型的class
public class Test03 {
   public static void main(String[] args) {
       Class c1 = Object.class;   // 类
       Class c2 = Comparable.class;   // 接口
       Class c3 = String[].class;    // 一维数组
       Class c4 = int[][].class; // 二维数组
       Class c5 = Override.class; // 注解
       Class c6 = ElementType.class;    // 枚举
       Class c7 = InternalError.class;  //基本数据类型
       Class c8 = void.class; //void
       Class c9 = Class.class;  // Class

       System.out.println(c1);
       System.out.println(c2);
       System.out.println(c3);
       System.out.println(c4);
       System.out.println(c5);
       System.out.println(c6);
       System.out.println(c7);
       System.out.println(c8);
       System.out.println(c9);

  }
}

类加载内存分析

加载:将class文件字节码内容加载到内存中,并将这些静态数据转换成方法区的运行时数据结构然后生成一个代表这个类的java.lang.Class对象。

链接:将Java类的二进制代码合并到JVM的运行状态之中的过程。

  • 验证:确保加载的类信息符合JVM规范,没有安全方面的问题
  • 准备:正式为类变量(static)分配内存并设置类变量默认初始值的阶段,这些内存都将在方法区中进分配。
  • 解析:虚拟机常量池内的符号引用(常量名)替换为直接引用(地址)的过程。

初始化:

  • 执行类构造器()方法的过程。类构造器()方法是由编译期自动收集类中所有类变量的赋值动作和静态代码块中的语句合并产生的。(类构造器是构造类信息的,不是构造该类对象的构造器)。
  • 当初始化一个类的时候,如果发现其父类还没有进行初始化,则需要先触发其父类的初始化。
  • 虚拟机会保证一个类的()方法在多线程环境中被正确加锁和同步。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package reflection;

public class Test04 {
   public static void main(String[] args) {
       A a = new A();
       System.out.println(a.m);

       /*
       1. 加载到内存,会产生一个类对应class对象
       2.链接,链接结束后 m = 0
       3. 初始化
           <clinit>(){
               System.out.println("A类的无参构造初始化");
               m = 300;
               m = 100;
           }
           m = 100;
        */
  }
}

class A {
   static {
       System.out.println("A类");
       m = 300;
  }
   /*
   m ==> 300
   m ==> 100
    */
   static int m = 100;

   public A() {
       System.out.println("A类的无参构造初始化");
  }
}

类初始化

类的主动引用(一定会发生类的初始化)

  • 当虚拟机启动,先初始化main方法所在的类
  • new一个类的对象
  • 调用类的静态成员(除了final常量)和静态方法
  • 使用java.lang.reflect包的方法对类进行反射调用
  • 当初始化一个类,如果其父类没有被初始化,则先会初始化它的父类

类的被动引用(不会发生类的初始化)

  • 当访问一个静态域时,只有真正声明这个域的类才会被初始化。如:当通过子类引用父类的静态变量,不会导致子类初始化
  • 通过数组定义类引用,不会触发此类的初始化
  • 引用常量不会触发此类的初始化(常量在链接阶段就存入调用类的常量池中了)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package reflection;

// 类什么时候会初始化
public class Test05 {
static {
System.out.println("Main类被加载");
}

public static void main(String[] args) throws ClassNotFoundException {
// 1.主动引用
// Son son = new Son();

// 反射也会主动引用
// Class.forName("reflection.Son");

// 不会产生类的引用的方法
// System.out.println(Son.b);

// System.out.println(Son.M);


}
}

class Father {
static int b = 2;

static {
System.out.println("父类被加载");
}
}

class Son extends Father {
static {
System.out.println("子类被加载");
m = 300;
}

static int m = 100;

static final int M = 1;
}

类加载器的作用

类加载的作用:将class文件字节码内容加载到内存中,并将这些静态数据转换成方法区的运行时数据结构,然后在堆中生成一个代表这个类的java.lang.Class对象,作为方法区中类数据的访问入口。

类缓存:标准的JavaSE类加载器可以按要求查找类,但一旦某个类被加载到类加载器中,它将维持加载(缓存)一段时间。不过JVM垃圾回收机制可以回收这些Class对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package reflection;

public class Test06 {
public static void main(String[] args) throws ClassNotFoundException {
// 获取系统类的加载器
ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader();
System.out.println(systemClassLoader);

// 获取系统类的加载器的父类加载器 --> 扩展类加载器
ClassLoader parent = systemClassLoader.getParent();
System.out.println(parent);

// 获取拓展类的加载器的父类加载器 --> 根加载器(C/c++)
ClassLoader parentParent = parent.getParent();
System.out.println(parentParent);

// 测试当前类是那个加载器加载的
ClassLoader classLoader = Class.forName("reflection.Test06").getClassLoader();
System.out.println(classLoader);

// 测试JDK内置的类是谁加载的
ClassLoader classLoader1 = Class.forName("java.lang.Object").getClassLoader();
System.out.println(classLoader1);

// 如何获得系统类加载器可以加载的路径
System.out.println(System.getProperty("java.class.path"));
}
}

创建运行时类的对象 Java.Reflection

获取运行时类的完整结构

通过反射获取运行时的完整结构

Field、Method、Construct、Superclass、Interface、Annotation

  • 实现的全部接口
  • 所继承的父类
  • 全部的构造器
  • 全部的方法
  • 全部的Field
  • 注解
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package reflection;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class Test07 {
public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, NoSuchMethodException {

Class c1 = Class.forName("reflection.User");

// 获得类的名字
System.out.println(c1.getName()); // 包名 + 类名
System.out.println(c1.getSimpleName()); // 类名

System.out.println("==============================================================================");

// 获得类的属性
Field[] fields = c1.getFields(); // getFields 只能public属性

Field[] declaredFields = c1.getDeclaredFields(); // getDeclaredFields 全部属性
for (Field declaredField : declaredFields) {
System.out.println(declaredField);
}

// 获取指定属性的值
Field name = c1.getDeclaredField("name");
System.out.println(name);

System.out.println("==============================================================================");

// 获得类的方法
Method[] methods = c1.getMethods(); // 获得本类及其父类的全部public方法
for (Method method : methods) {
System.out.println("getMethods:" + method);
}

Method[] declaredMethods = c1.getDeclaredMethods(); // 获得本类的所有方法
for (Method declaredMethod : declaredMethods) {
System.out.println("getDeclaredMethods:" + declaredMethod);
}

// 获得指定方法
// 重载
Method getName = c1.getMethod("getName", null);
Method setName = c1.getMethod("setName", String.class);
System.out.println(getName);
System.out.println(setName);

// 获得构造器
System.out.println("==============================================================================");
Constructor[] constructors = c1.getConstructors(); // public
for (Constructor constructor : constructors) {
System.out.println("getConstructors:" + constructor);
}
Constructor[] declaredConstructors = c1.getDeclaredConstructors(); // 所有
for (Constructor declaredConstructor : declaredConstructors) {
System.out.println("getDeclaredConstructors:" + declaredConstructor);
}

// 获得指定构造器
Constructor declaredConstructor = c1.getDeclaredConstructor(String.class, int.class, int.class);
System.out.println("指定:"+declaredConstructor);

}
}

有了Class对象,能做什么?

创建类的对象:调用Class对象的newlnstance()方法

  1. 类必须有一个无参数的构造器。
  2. 类的构造器的访问权限需要足够

思考?难道没有无参的构造器就不能创建对象了吗?只要在操作的时候明确的调用类中的构造器,并将参数传递进去之后,才可以实例化操作。

步骤如下:

  1. 通过Class类的getDeclaredConstructor(Class … parameterTypes)取得本类的指定形参类型的构造器
  2. 向构造器的形参中传递一个对象数组进去,里面包含了构造器中所需的各个参数。
  3. 通过Constructor实例化对象

调用指定的方法

通过反射,调用类中的方法,通过Method类完成。

  1. 通过Class类的getMethod(String name,Class…parameterTypes)方法取得一个Method对象,并设置此方法操作时所需要的参数类型。
  2. 之后使用Object invoke(Object obj, Object[] args)进行调用,并向方法中传递要设置的obj对象的参数信息。
Object invoke(Object obj, Object … args)
  • Object对应原方法的返回值,若原方法无返回值,此过返回nul
  • 若原方法若为静态方法,此时形参object obj可为null
  • 若原方法形参列表为空,则Object[] args为null
  • 若原方法声明为private,则需要在调用此invoke()方法前,显式调用方法对象的setAccessible(true)方法,将可访问private的方法。
setAccessible
  • Method和Field、Constructor对象都有setAccessible()方法。
  • setAccessible作用是启动和禁用访问安全检查的开关。
  • 参数值为true则指示反射的对象在使用时应该取消Java语言访问检查。
    • 提高反射的效率。如果代码中必须用反射,而该句代码需要频繁的被调用,那么请设置为true。
    • 使得原本无法访问的私有成员也可以访问
  • 参数值为false则指示反射的对象应该实施Java语言访问检查
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package reflection;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

// 分析性能问题
public class Test09 {

public static void main(String[] args) throws InvocationTargetException, NoSuchMethodException, IllegalAccessException {
test01();
test02();
test03();
}

// 普通方式调用
public static void test01() {
User user = new User();
long startTime = System.currentTimeMillis();

for (int i = 0; i < 1000000000; i++) {
user.getName();
}

long endTime = System.currentTimeMillis();

System.out.println("普通方式:" + (endTime - startTime) + "ms");
}


// 反射方式调用
public static void test02() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
User user = new User();
Class c1 = user.getClass();
Method getName = c1.getDeclaredMethod("getName", null);
long startTime = System.currentTimeMillis();

for (int i = 0; i < 1000000000; i++) {
getName.invoke(user, null);
}

long endTime = System.currentTimeMillis();

System.out.println("反射方式:" + (endTime - startTime) + "ms");
}

// 反射方式调用 关闭检测
public static void test03() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
User user = new User();
Class c1 = user.getClass();
Method getName = c1.getDeclaredMethod("getName", null);
getName.setAccessible(true);
long startTime = System.currentTimeMillis();

for (int i = 0; i < 1000000000; i++) {
getName.invoke(user, null);
}

long endTime = System.currentTimeMillis();

System.out.println("关闭检测:" + (endTime - startTime) + "ms");
}
}

反射操作泛型

  • Java采用泛型擦除的机制来引入泛型,Java中的泛型仅仅是给编译器javac使用的,确保数据的安全性和免去强制类型转换问题,但是,一旦编译完成,所有和泛型有关的类型全部擦除
  • 为了通过反射操作这些类型,Java新增了ParameterizedType , GenericArrayType ,TypeVariable和 WildcardType几种类型来代表不能被归一到Class类中的类型但是又和原始类型齐名的类型。
  • ParameterizedType:表示一种参数化类型,比如Collection
  • GenericArrayType:表示一种元素类型是参数化类型或者类型变量的数组类型TypeVariable:是各种类型变量的公共父接口
  • WildcardType:代表一种通配符类型表达式
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package reflection;

import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;

// 通过反射获取泛型
public class Test10 {

public static void main(String[] args) throws NoSuchMethodException {
Method method01 = Test10.class.getMethod("test01", Map.class, List.class);
Type[] genericParameterTypes = method01.getGenericParameterTypes();
for (Type genericParameterType : genericParameterTypes) {
System.out.println("##:" + genericParameterType);
if (genericParameterType instanceof ParameterizedType) {
Type[] actualTypeArguments = ((ParameterizedType) genericParameterType).getActualTypeArguments();
for (Type actualTypeArgument : actualTypeArguments) {
System.out.println(actualTypeArgument);
}
}
}

Method method02 = Test10.class.getMethod("test02", null);
Type genericReturnType = method02.getGenericReturnType();
if (genericReturnType instanceof ParameterizedType) {
Type[] actualTypeArguments = ((ParameterizedType) genericReturnType).getActualTypeArguments();
for (Type actualTypeArgument : actualTypeArguments) {
System.out.println("@@:"+actualTypeArgument);
}
}
}

public void test01(Map<String, User> map, List<User> list) {
System.out.println("test01");
}

public Map<String, User> test02() {
System.out.println("test02");
return null;
}
}

反射操作注解

  • getAnnotations
  • getAnnotation

ORM

Object relationship Mapping –> 对象关系映射

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package reflection;

import java.lang.annotation.*;
import java.lang.reflect.Field;

// 反射注解操作
public class Test11 {
public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException {

Class c1 = Class.forName("reflection.Student2");

// 通过反射获取注解
Annotation[] annotations = c1.getAnnotations();
for (Annotation annotation : annotations) {
System.out.println(annotation);
}

// 获得注解的value的值
TableStudent tableStudent = (TableStudent) c1.getAnnotation(TableStudent.class);
String value = tableStudent.value();
System.out.println(value);

// 获得类指定的注解
Field f = c1.getDeclaredField("id");
FieldStudent annotation = f.getAnnotation(FieldStudent.class);
System.out.println(annotation.columnName());
System.out.println(annotation.type());
System.out.println(annotation.length());
}
}

@TableStudent("db_student")
class Student2 {

@FieldStudent(columnName = "db_id", type = "int", length = 10)
private int id;
@FieldStudent(columnName = "db_age", type = "int", length = 10)
private int age;
@FieldStudent(columnName = "db_name", type = "varchar", length = 3)
private String name;

public Student2() {
}

public Student2(int id, int age, String name) {
this.id = id;
this.age = age;
this.name = name;
}

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

@Override
public String toString() {
return "Student2{" +
"id=" + id +
", age=" + age +
", name='" + name + '\'' +
'}';
}
}

// 类名的注解
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface TableStudent {
String value();
}

// 属性的注解
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface FieldStudent {
String columnName();

String type();

int length();
}

总结

注解->自定义注解->Class类->类加载机制->反射的实际应用