Java注解和反射
注解(Annotation)
注解入门
Annotation是从JDK5.0开始引入的新技术,注解和反射是所有框架的底层实现方式。注解和注释相当类似,但是注解不仅可以给人看,也能给程序看。
Annotation的作用
- Annotation不是程序本身,但是可以对程序作出解释、这一点和注释( comment没什么区别)
- 可以被其他程序比如:编译器等读取。
Annotation的格式
注解是以”@注释名”在代码中存在的,还可以添加一些参数值,例如:@SuppressWarnings(value="unchecked")
Annotation在哪里使用
可以附加在 package, class, method,feld等上面,相当于给他们添加了额外的辅助信息,我们可以通过反射机制编程实现对这些元数据的访问。
Annotation的格式
内置注解
1.@Override
:定义在java.lang.Override
中,此注释只适用于修辞方法,表示一个方法声明打算重写超类中的另一个方法声明。
2.@Deprecated
:定义在java.lang.Deprecated
中,此注释可以用于修辞方法,属性,类,表示不鼓励程序员使用这样的元素,通常是因为它很危险或者存在更好的选择
3.@SuppressWarnings
:定义在java.lang.SuppressWarnings
中,用来抑制编译时的警告信息(该注解可以传入参数)
- 与前两个注释有所不同,你需要添加一个参数オ能正确使用,这些参数都是已经定义好了的,我们选择性的使用就好了。
@SuppressWarnings("all")
@SuppressWarnings("unchecked")
@SuppressWarnings("value={"unchecked", "deprecation")
- 等…
注解相关代码练习:
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 com.everweekup.Annotation;
import java.util.ArrayList; import java.util.List;
public class Test01 extends Object{ @Override public String toString() { return super.toString(); }
@Deprecated public static void test(){ System.out.println("有更好的或者已废弃"); }
@SuppressWarnings("all") public void test02(){ List list = new ArrayList(); }
public static void main(String[] args) { test(); } }
|
自定义注解,元注解
元注解的作用就是负责注解其他注解,Java定义了4个标准的meta- annotation类型,他们被用来提供对其他 annotation类型作说明。
这些类型和它们所支持的类在iava.lang.annotation包中可以找到。(@ Target,@ Retention,@Documented, @Inherited)
@Target
:用于描述注解的使用范围(即被描述的注解可以用在什么地方)
@Retention
:表示需要在什么级別保存该注释信息,用于描述注解的生命周期
@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 24 25
| package com.everweekup.Annotation;
import java.lang.annotation.*;
public class MetaAnnotationTest {
@MyAnnotation public static void test(){} }
@Target(value = {ElementType.METHOD, ElementType.TYPE})
@Retention(value = RetentionPolicy.RUNTIME)
@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
| package com.everweekup.Annotation;
import javax.lang.model.element.TypeElement; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target;
public class Test03 { @MyAnnotation2(name = "hj") public void test(){}
@MyAnnotation3("Str") public void test2(){} }
@Target({ElementType.TYPE, ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @interface MyAnnotation2{ String name() default ""; int age() default 0; int id() default -1;
String[] schools() default {"1", "默认注解"}; }
@Target({ElementType.TYPE, ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @interface MyAnnotation3{ String value(); }
|
反射机制
反射机制使得java变得动态起来。使得java即使在运行阶段也能插入程序代码而不影响原程序运行。
静态 VS 动态语言
动态语言
是一类在运行时可以改变其结构的语言:例如新的函数、对象、甚至代码可以被引进,已有的函数可以被删除或是其他结构上的变化。通俗点说就是在运行时代码可以根据某些条件改变自身结构。
主要动态语言: Object-C、C#、 Javascript、PHP、 Python等。

静态语言
与动态语言相对应的,运行时结构不可变的语言就是静态语言。如Java、C、C++。
Java不是动态语言,但Java可以称之为“准动态语言”。即Java有一定的动态性,我们可以利用反射机制获得类似动态语言的特性。Java的动态性让编程的时侯更灵活!
Java反射机制概述
Reflection(反射)是Java被视为动态语言的关键,反射机制允许程序在执行期借助于 Reflection API 取得任何类的内部信息,并能直接操作任意对象的内部属性及方法。
1
| Class c = Class.forName("java.lang.String")
|
加载完类之后,在堆内存的方法区中就产生了ー个 Class 类型的对象(一个类只有一个 Class 对象),这个对象就包含了完整的类的结构信息。我们可以通过这个对象看到类的结构。这个对象就像一面镜子,透过这个镜子看到类的结构,所以,我们形象的称之为:反射
正常方式:引入需要的“包类”名称 =>通过new实例化=>取得实例化对象
反射方式:实例化对象=>getClass()
方法=>得到完整的“包类”名称
Java反射机制提供的功能
- 在运行时判断任意一个对象所属的类
- 在运行时构造任意一个类的对象
- 在运行时判断任意一个类所具有的成员变量和方法
- 在运行时获取泛型信息
- 在运行时调用任意一个对象的成员变量和方法
- 在运行时处理注解
- 生成动态代理(AOP)
- ……
Java反射的优点和缺点
优点
可以实现动态创建对象和编译,体现出很大的灵活性
缺点
对性能有影响。使用反射基本上是一种解释操作,我们可以告诉JVM,我们希望做什么并且它满足我们的要求。这类操作总是慢于直接执行相同的操作。
反射相关的主要API
java.lang.Class
:代表一个类
java.lang.reflect.Method
:代表类的方法
java.lang.reflect.Field
:代表类的成员变量
java.lang.reflect.Constructor
:代表类的构造器
……
代码实操:
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 com.everweekup.Reflection;
public class Test01{ public static void main(String[] args) throws ClassNotFoundException { Class c1 = Class.forName("com.everweekup.Reflection.User"); System.out.println(c1);
Class c2 = Class.forName("com.everweekup.Reflection.User"); Class c3 = Class.forName("com.everweekup.Reflection.User"); Class c4 = Class.forName("com.everweekup.Reflection.User");
System.out.println(c2.hashCode()); System.out.println(c3.hashCode()); System.out.println(c4.hashCode());
} }
class User { private String name; private int id; private int age;
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类
Java在Object类中定义了以下的方法,此方法将被所有子类继承:
public final Class getClass()
以上的方法返回值的类型是一个 Class类,此类是Java反射的源头,实际上所谓反射从程序的运行结果来看也很好理解,即:可以通过对象反射求出类的名称

反射就是通过对象去得到Class类,每个对象通过getClass可以得到类的所有信息。
理解Class类并获取Class实例
对象照镜子后可以得到的信息:某个类的属性、方法和构造器、某个类到底实现了哪些接口对于每个类而言,JRE都为其保留一个不变的Cass类型的对象。一个Class对象包含了特定某个结构( class/ interface/enum/ annotation/primitive type/void[])的有关信息。
- Class本身也是一个类
- Class对象只能由系统建立对象
- 一个加载的类在JVM中只会有一个 Class实例
- 一个Class对象对应的是一个加载到JVM中的一个. class文件
- 每个类的实例都会记得自己是由哪个Class实例所生成
- 通过Class可以完整地得到一个类中的所有被加载的结构
- Class类是 Reflection的根源,针对任何你想动态加載运行的类)唯有先获得相应的
Class对象
Class类的常用方法

获取Class类的实例
- 若已知具体的类,通过类的class属性获取,该方法最为安全可靠,程序性能最高。
Class clazz = Person.class
- 已知某个类的实例,调用该实例的
getClass()
方法获取Class对象
Person person = new Person(name)
Class clazz = person.getClass()
- 已知一个类的全类名,且该类在类路径下,可通过Class类的静态方法forName()获取,可能抛出
ClassNotFoundException
Class clazz = Class.forName("com.everweekup.www.Demo01")
- 内置基本数据类型可以直接用类名
.Type
- 还可以利用ClassLoader
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
| package com.everweekup.Reflection;
public class Test03 { public static void main(String[] args) throws ClassNotFoundException { Person person = new Person(); System.out.println("这个人是:" + person.name);
Class c1 = person.getClass(); System.out.println(c1.hashCode());
Class c2 = Class.forName("com.everweekup.Reflection.Student"); System.out.println(c2.hashCode());
Class<Student> c3 = Student.class; System.out.println(c3.hashCode());
Class c4 = Integer.TYPE; System.out.println(c4); Class c5 = c2.getSuperclass(); System.out.println(c5); } }
class Person{ public String name;
public Person() { }
public Person(String name) { this.name = name; }
@Override public String toString() { return "Test03{" + "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 30 31 32 33 34 35 36
| package com.everweekup.Reflection;
import java.lang.annotation.ElementType;
public class AllClassTest { 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 = Integer.class; Class c8 = void.class; Class c9 = 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);
int[] a = new int[]{1,2,3}; int[] b = new int[]{4,5,6};
System.out.println(a.getClass().hashCode()); System.out.println(b.getClass().hashCode()); } }
|
类的加载与ClassLoader(双亲委派机制)
Java内存分析

类的加载过程
当程序主动使用某个类时,如果该类还未被加载到内存中,则系统会通过如下三个步骤来对该类进行初始化。

类的加载与ClassLoader的理解
加载:将 class文件字节码内容加载到内存中,并将这些静态数据转換成方法区的运行时数据结构然后生成一个代表这个类的java.lang.Class
对象。
链接:将Java类的二进制代码合并到 JVM 的运行状态之中的过程。
- 验证:确保加载的类信息符合 JVM 规范,没有安全方面的问题
- 准备:正式为类变量( static)分配内存并设置类变量默认初始值的阶段,这些内存都将在方法区中进行分配
- 解析:虚拟机常量池内的符号引用(常量名)替换为直接引用(地址)的过程初始化
初始化:
- 执行类构造器
< clinit>()
方法的过程。类构造器< clinit>()
方法是由编译期自动收集类中所有类变量的赋值动作和静态代码块中的语句合并产生的。(类构造器是构造类信息的,不是构造该类对象的构造器)
- 当初始化一个类的时候,如果发现其父类还没有进行初始化,则需要先触发其父类的初始化
- 虚拟机会保证一个类的
<clinit>()
方法在多线程环境中被正确加锁和同步。
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
| package com.everweekup.Reflection;
public class Test05 { public static void main(String[] args) { A a = new A(); System.out.println(A.m);
} }
class A{ static { System.out.println("A类静态代码块初始化"); m = 300; }
static int m = 100;
public A(){ System.out.println("A类的无参构造初始化"); } }
|
内存分析:

Class是在类加载过程中产生的,比如类加载到方法区,在堆生成一个Class,能够反射到原类以及类结构。然后为类变量(静态才可)分配内存,再链接成功后,设置类变量的默认初始值。接着初始化类(类构造器有<clinit>()
方法去合并静态变量)。
分析类初始化
什么时候会发生类初始化
1.类的主动引用(一定会发生类的初始化)
- 当虚拟机启动,先初始化main方法所在的类
- new一个类对象
- 调用类的静态成员(除了final常量)和静态方法
- 使用
java.lang.reflect
包的方法对类进行反射调用
- 当初始化一个类,如果其父类没有被初始化,则先会初始化它的父类
2.类的被动引用(不会发生类的初始化)
- 当访问一个静态域时,只有真正声明这个域的类才会被初始化。如:当通过子类引用父类的静态变量,不会导致子类初始化
- 通过数组定义类引用,不会触及此类的初始化
- 引用常量不会触及此类的初始化(常量在链接阶段就存入调用类的常量池中了)
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
| package com.everweekup.Reflection;
public class Test06 { static{ System.out.println("main类被加载"); } public static void main(String[] args) throws ClassNotFoundException {
System.out.println(Child.b);
Child[] array = new Child[5];
System.out.println(Child.M);
} }
class Father{ static int b =2;
static{ System.out.println("父类被加载"); } }
class Child extends Father{ static{ System.out.println("子类被加载"); m = 300; }
static int m = 100; static final int M =1; }
|
类加载器
类加载器的作用
类加载的作用:将 class文件字节码内容加载到内存中,并将这些静态数据转換成方法区的运行时数据结构,然后在堆中生成一个代表这个类的iava. lang.Class
对象,作为方法区中类数据的访问入口。
类缓存:标准的 JavaSE类加载器可以按要求査找类,但一旦某个类被加载到类加载器中,它将维持加载(缓存)一段时间。不过 JVM 垃圾回收机制可以回收这些 Class 对象。

类加载器作用是用来把类(class)装载进内存的。 JVM规范定义了如下类型的类加载器。

双亲委派机制
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
| package com.everweekup.Reflection;
public class Test07 { public static void main(String[] args) throws ClassNotFoundException { ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader(); System.out.println(systemClassLoader);
ClassLoader parent = systemClassLoader.getParent(); System.out.println(parent);
ClassLoader parent1 = parent.getParent(); System.out.println(parent1);
ClassLoader classLoader = Class.forName("com.everweekup.Reflection.Test07").getClassLoader(); System.out.println(classLoader);
ClassLoader classLoader1 = Class.forName("java.lang.Object").getClassLoader(); System.out.println(classLoader1);
System.out.println(System.getProperty("java.class.path"));
} }
|
获取运行时类的完整结构
获取泛型、注解。通过反射获取运行时类的完整结构:
Field
、Method
、Constructor
、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 67 68 69 70 71 72 73
| package com.everweekup.Reflection;
import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method;
public class Test08 { public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, NoSuchMethodException { Class c1 = Class.forName("com.everweekup.Reflection.User");
System.out.println(c1.getName()); System.out.println(c1.getSimpleName());
User user = new User(); c1 = user.getClass(); System.out.println(c1);
Field[] fields = c1.getDeclaredFields(); for (Field field : fields) { System.out.println(field);
}
Field name = c1.getDeclaredField("name"); System.out.println(name);
System.out.println("================="); Method[] methods = c1.getMethods(); for (Method method : methods) { System.out.println("正常的" + method); }
methods = c1.getDeclaredMethods(); for (Method method : methods) { System.out.println("getDeclaredMethods:" + method); }
Method getName = c1.getMethod("getName",null); System.out.println(getName);
Method setName = c1.getMethod("setName",String.class); System.out.println(setName);
System.out.println("=================="); Constructor[] constructor = c1.getConstructors(); for (Constructor constructor1 : constructor) { System.out.println(constructor1); }
constructor = c1.getDeclaredConstructors(); for (Constructor constructor1 : constructor) { System.out.println("$"+constructor1); }
c1.getDeclaredConstructor(String.class, int.class, int.class); System.out.println("指定的"+c1); } }
|
小结
创建运行时类的对象
反射机制实现。(还有一个clone)
在程序运行时,仍然可以新建类,注入程序(外挂原理)
有了Class对象,能做什么?
创建类的对象:调用 Class对象的newInstance()
方法
类必须有一个无参数的构造器。
类的构造器的访问权限需要足够
思考:
难道没有无参构造器的类就不能创建对象了吗?
答:只要在操作的时候明确的调用类中的构造器,并将参数传递进去之后,才可以实例化操作。步骤如下
- 通过Class类的 getDeclaredConstructor(Class … parameterTypes)取得本类的指定形参类型的构造器
- 向构造器的形参中传递一个对象数组进去,里面包含了构造器中所需的各个参数。
- 通过 constructors实例化对象
通过反射动态创建对象
调用指定的方法
通过反射,调用类中的方法,通过 Method类完成。
- 通过 Class类的 getMethod(String name, Class … parameterTypes)方法取得一个 Method对象,并设置此方法操作时所需要的参数类型。
- 之后使用 Object invoke( Object obj, Object[] args)进行调用,并向方法中传递要设置的obj对象的参数信息。

Object invoke(Object obj, Object ... args)
- Object:对应原方法的返回值,若原方法无法返回值,此时返回null
- 若原方法为静态方法,此时形参Object obj可为null
- 若原方法形参列表为空,则Object[] args 为null
- 若原方法声明为private,则需要在调用此
invoke()
方法前,显示调用方对象的setAccessible(true)
方法,以访问private的方法
setAccessible
Method 和 Fied、 Constructor 对象都有 setAccessible()
方法。setAccessible()
作用是启动和禁用访问安全检查的开关。
参数值为true则指示反射的对象在使用时应该取消Java语言访问检査。
参数值为 falsel则指示反射的对象应该实施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
| package com.everweekup.Reflection;
import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method;
public class Test09 { public static void main(String[] args) throws IllegalAccessException, InstantiationException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException { Class c1 = Class.forName("com.everweekup.Reflection.User");
User user3 = (User) c1.newInstance(); Method setName = c1.getDeclaredMethod("setName", String.class); setName.invoke(user3, "hj");
System.out.println(user3.getName());
User user4 = (User)c1.newInstance(); Field name = c1.getDeclaredField("name");
name.setAccessible(true); name.set(user4,"hj"); System.out.println(user4.getName()); } }
|
性能对比分析
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
| package com.everweekup.Reflection;
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method;
public class Test10 {
public static void test01() { User user = new User();
long starttime = System.currentTimeMillis(); for (int i = 0; i < 100000000; i++) { user.getName(); } long endtime = System.currentTimeMillis();
System.out.println("普通方法执行一亿次耗时:" + (endtime - starttime)+"ms"); }
public static void test02() throws InvocationTargetException, IllegalAccessException, NoSuchMethodException { User user = new User(); Class c1 = user.getClass();
Method getName = c1.getDeclaredMethod("getName", null);
long starttime = System.currentTimeMillis(); for (int i = 0; i < 100000000; i++) { getName.invoke(user, null); } long endtime = System.currentTimeMillis();
System.out.println("反射方法执行一亿次耗时:" + (endtime - starttime)+"ms"); }
public static void test03() throws InvocationTargetException, IllegalAccessException, NoSuchMethodException { 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 < 100000000; i++) { getName.invoke(user, null); } long endtime = System.currentTimeMillis();
System.out.println("关闭检测执行一亿次耗时:" + (endtime - starttime)+"ms"); }
public static void main(String[] args) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException { test01(); test02(); test03(); } }
|
获取泛型信息
反射操作泛型
Java采用泛型擦除的机制来引入泛型,Java中的泛型仅仅是给编译器 javac 使用的,确保数据的安全性和免去强制类型转換问题,但是,一旦编译完成,所有和泛型有关的类型全部擦除。
为了通过反射操作这些类型,Java新增了 Parameterized Type, GenericArray TypeVariable 和 WildcardType几种类型来代表不能被归一到Class类中的类型但是又和原始类型齐名的类型。
- Parameterized Type:表示一种参数化类型,比如 Collection< String>
- GenericArray Type:表示一种元素类型是参数化类型或者类型变量的数组类型
- 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 44 45 46 47
| package com.everweekup.Reflection;
import sun.applet.Main;
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 Test11 {
public void test01(Map<String, User> map, List<User> list){
}
public Map<String, User> test02(){ System.out.println("test02"); return null; }
public static void main(String[] args) throws NoSuchMethodException { Method method = Test11.class.getMethod("test01", Map.class, List.class);
Type[] genericParameterType = method.getGenericParameterTypes(); for (Type type : genericParameterType) { System.out.println("#" + genericParameterType);
if(type instanceof ParameterizedType){ Type[] actualType = ((ParameterizedType) type).getActualTypeArguments(); for (Type type1 : actualType) { System.out.println(type1);
} } } } }
|
反射获取注解信息
反射操作注解
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
| package com.everweekup.Reflection;
import java.lang.annotation.*; import java.lang.reflect.Field;
public class Test12 { public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException { Class c1 = Class.forName("com.everweekup.Reflection.Student2");
Annotation[] annotation = c1.getAnnotations(); for (Annotation annotation1 : annotation) { System.out.println(annotation1); }
Table table = (Table) c1.getAnnotation(Table.class); String value = table.value(); System.out.println(value);
Field f = c1.getDeclaredField("name"); Fields annotations = f.getAnnotation(Fields.class); System.out.println(annotations.columnName()); System.out.println(annotations.type()); System.out.println(annotations.length());
} }
@Table("db_student") class Student2 { @Fields(columnName="db_id",type="int",length=10) private int id; @Fields(columnName="db_age",type="int",length=10) private int age; @Fields(columnName="db_name",type="vachar",length=10) 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 Table{ String value(); }
@Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) @interface Fields{ String columnName(); String type(); int length();
}
|
反射注解总结
- Annotation是从JDK5.0开始引入的新技术
Annotation的作用
- 不是程序本身,可以对程序作出解释、这一点和注释( comment没什么区别)
- 可以被其他程序(比如:编译器等)读取
Annotation的格式:
Annotation在哪里使用?
- 可以附加在 package, class, method,feld等上面,相当于给他们添加了额外的辅助信息
- 我们可以通过反射机制编程实现对这些元数据的访问
参考资料