注解和反射
注解(Annotation)是 jdk5 引入的新技术。
Anotation 的作用:可以对程序作出解释,可以被其它程序(比如编译器等)读取。
Annotation 的格式:注解是以”@注释名”在代码中存在的,还可以添加一些参数值。
Annotation 可以在 package,class,method,filed 等上面,相当于给它们添加了额外的辅助信息,可以通过反射机制来实现这些元数据的访问。
内置注解
@Override:定义在 java.long.Override 中,此注解只适用于修辞方法,表示一个方法声明打算重写超类中的另一个方法声明。
@Deprecated:定义在 java.long.Deprecated 中,此注解可用于修辞方法,属性,类表示不鼓励使用这样的元素。
@SuppressWarnings:定义在 java.long.SuppressWarnings 中,用来抑制编译时的警告信息。需添加一个参数才能正常使用。
元注解
元注解的作用就是负责注解其他注解,Java 定义了 4 个标准的 meta-annotation 类型,它们被用来提供对其他 annotation 类型作说明。
这些类型和它所支持的类在 java.long.annotation 包中可恶意找到(@Target,@Retention,@Decumented,@Inherited)。
@Target:用于描述注解使用的范围(即:被描述的注解可以用在什么地方)。
@Retention:表示需要在什么级别保存该注释信息用于描述注解的生命周期(source<class<runtime)。
@Decumented:说明该注解将被包含在 javadoc 中。
@Inherite:说明子类可以继承父类中的该注解。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| package com.annotation; import java.lang.annotation.*;
@MyAnnotation public class Test02 { public void test(){ } }
@Target(value = {ElementType.METHOD,ElementType.TYPE})
@Retention(value = RetentionPolicy.RUNTIME)
@Documented
@Inherited @interface MyAnnotation{ }
|
自定义注解
使用@interface 自定义注解时,自动继承了 java.long.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
| package com.annotation; import java.lang.annotation.*;
public class Test03 { @MyAnnotation2(name = "zz",school = {"西北","华中"}) public void test(){ } @MyAnnotation3("周") 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[] school(); } @Target({ElementType.TYPE,ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @interface MyAnnotation3{ String value(); }
|
反射机制
Reflection(反射)是 Java 被视为动态语言的关键,反射机制允许程序在执行期间借助于 Reflection API 取得任何类的内部消息,并能直接操作任意对象的内部属性及方法。
加载完类之后,在堆内存的方法区中就产生了一个 Class 类型的对象(一个类只有一个 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
| package com.annotation;
public class test04 { public static void main(String[] args) throws ClassNotFoundException { Class c1 = Class.forName("com.annotation.User"); System.out.println(c1); Class c2 = Class.forName("com.annotation.User"); Class c3 = Class.forName("com.annotation.User"); System.out.println(c2.hashCode()); System.out.println(c3.hashCode()); } }
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 类
对象通过反射得到的信息:某个类的属性,方法和构造器,某个类到底实现了哪些接口;对于每个类而言,JRE 都为其保留一个不变的 Class 类型的对象,一个 Class 包含了特定某个结构的有关信息。
- Class 本身也是一个类,Class 对象只能由系统建立对象。
- 一个加载的类在 JVM 中只有一个 Class 实列,一个 Class 对象对应的是一个加载到 JVM 中的.class 文件。
- 每个类的实例都会记得自己是哪个 Class 实例所生成,通过 Class 对象可以完整地得到一个类中所有被加载的结构。
- Class 类是 Reflecion 的根源,针对任何你想动态加载运行的类,唯有先获得相应的 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
| package com.annotation;
public class Test05 { 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()); Class c2 = Class.forName("com.annotation.Student"); System.out.println(c2.hashCode()); Class c3 = Student.class; System.out.println(c3.hashCode()); Class c4 = Integer.TYPE; System.out.println(c4); Class c5 = c1.getSuperclass(); System.out.println(c5); } } class Person{ String name; public Person(){ } public Person(String name) { this.name = name; } @Override public String toString() { return "Person{" + "name='" + name + '\'' + '}'; } } class Student extends Person{ public Student(){ this.name = "学生"; } } class Teacher extends Person{ public Teacher(){ this.name = "老师"; } }
|
Class,接口,数组,枚举,注解,基本数据类型,void 都有 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
| package com.annotation; import java.lang.annotation.ElementType;
public class Test06 { 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[10]; int[] b = new int[100]; System.out.println(a.getClass().hashCode()); System.out.println(b.getClass().hashCode()); } }
|
类的加载过程
当程序主动使用某个类时,如果该类还未加载到内存中,则系统会通过如下三个步骤来对类进行初始化。
- 类的加载:将类的 class 文件读入内存,并将这些静态数据转化成方法区运行时的数据结构,然后为之创建一个 java.long.Class 对象,此过程由类加载器完成。
- 类的链接:将类的二进制数据合并到 JVM 中。
- 验证:确保加载的类的信息符合 JVM 规范,没有安全方面问题。
- 准备:正式为类变量(staic)分配内存并设置类变量默认初始值,这些内存都将在方法区中分配。解析:虚拟机
- 量池内的符号引用(常量名)替换为直接引用(地址)的过程。
- 类的初始化:JVM 负责对类进行初始化。
- 执行类构造器
<clinit>()方法的过程,类构造器<clinit>()方法是由编译期自动收集类中所有类变量的赋值动作和静态代码块中的语句合并产生的。(类构造器是构造类信息的,不是构造该类对象的)
- 当初始化一个类时,如果发现其父类还没有进行初始化,则需要先触发其父类的初始化。
- 虚拟机会保证一个类的
<clinit>()方法在多线程环境中被正确加锁和同步。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| package com.annotation;
public class Test07 { public static void main(String[] args) { A a = new A(); System.out.println(A.m); } } class A{ static { System.out.println("A类的静态代码块初始化"); m = 88; } static int m = 100; public A(){ System.out.println("A类的无参构造初始化"); } }
|
类初始化
类的主动引用(一定会发生类的初始化)
- 当虚拟机启动,先初始化 main 方法所在的类。、
- new 一个类的对象。
- 调用类的静态成员(除了 final 常量)和静态方法。
- 使用 java.long.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
| package com.annotation;
public class Test08 { static { System.out.println("main类被加载"); } public static void main(String[] args) throws ClassNotFoundException { System.out.println(Son.M); } } class Father{ static int b = 2; static { System.out.println("父类被加载"); } } class Son extends Father{ static { System.out.println("子类被加载"); } static int a = 88; static final int M = 1; }
|
类加载器
类加载的作用:将 class 文件字节码加载到内存中,并将这些静态的数据转化成方法区运行时的数据结构,然后在堆中生成一个代表这个类的 Class 对象,作为方法区中类数据的访问入口。
类缓存:标准的 JavaSE 类加载器可以按要求查找类,但一旦某个类被加载到类加载器中,它将维持加载(缓存)一段时间,不过 JVM 垃圾回收机制可以回收这些 Class 对象。
JVM 定义了如下类型的类加载器:
- 引导类(根)加载器:用 C++编写,是 JVM 自带的类加载器,负责 Java 平台核心库,用来装载核心类库,该加载器无法直接获取。
- 拓展类加载器:负责 jre/lib/ext 目录下的 jar 包或 D java.ext.dirs 指定目录下的 jar 包装入工作库。
- 系统类加载器:负责 Java-classpath 或 D java.class.path 所指的目录下的类与 jar 包装入工作库,是最常用的加载器。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| package com.annotation; public class Test09 { 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.annotation.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")); } }
|
获取类运行时结构
通过反射获取运行时类的完整结构:FieId,Method,Constructor,Superclass,Interface,Annotation。
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
| package com.annotation; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method;
public class Test10 { public static void main(String[] args) throws Exception { Class c1 = Class.forName("com.annotation.User"); System.out.println(c1.getName()); System.out.println(c1.getSimpleName()); Field[] fields = c1.getFields(); 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); } System.out.println("================================"); Method[] declaredMethods = c1.getDeclaredMethods(); for (Method declaredMethod : declaredMethods) { System.out.println(declaredMethod); } System.out.println("================================"); 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(); for (Constructor constructor : constructors) { System.out.println(constructor); } Constructor[] declaredConstructors = c1.getDeclaredConstructors(); for (Constructor declaredConstructor : declaredConstructors) { System.out.println(declaredConstructor); } Constructor constructor = c1.getConstructor(String.class, int.class, int.class); System.out.println("指定:"+constructor); } }
|
动态创建对象执行方法
创建类的对象:调用 Class 对象的 newinstapce()方法
- 类必须有一个无参构造器。
- 类的构造器的访问权限足够。
没有无参构造器,操作类中的构造器时需要将参数传递进去,才可以实例化操作。
- 通过 Class 类的 getDeclaredConstructor()取得本类的指定形参类型的构造器。
- 向构造器的形参中传递一个对象数组进去,里面包含了构造器中所需的各个参数。
- 通过 Constructor 实例化对象。
私有的方法,字段,构造器:调用对象的 setAccessible(true)方法才可访问。关闭安全检测的开关。
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.annotation; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method;
public class Test11 { public static void main(String[] args) throws Exception{ Class c1 = Class.forName("com.annotation.User"); User user = (User) c1.newInstance(); Constructor constructor = c1.getDeclaredConstructor(String.class, int.class, int.class); User user2 = (User) constructor.newInstance("周", 22, 88); User user3 = (User) c1.newInstance(); Method setName = c1.getDeclaredMethod("setName", String.class); setName.invoke(user3,"周"); System.out.println(user3.getName()); User user4 = (User) c1.newInstance(); Field name = c1.getDeclaredField("name"); name.setAccessible(true); name.set(user4,"周2"); System.out.println(user4.getName()); } }
|
setAccessible 性能分析
setAccessible 的作用是启动和禁用安全检测的开关。
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
| package com.annotation; import java.lang.reflect.Method;
public class Test12 { 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 Exception { User user = new User(); Class c1 = Class.forName("com.annotation.User"); Method getName = c1.getMethod("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 Exception { User user = new User(); Class c1 = Class.forName("com.annotation.User"); Method getName = c1.getMethod("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 Exception { test01(); test02(); test03(); } }
|
获取泛型信息
Java 采用泛型擦除的机制来引入泛型,Java 中的泛型仅仅是给编译器 javac 使用的,确保数值的安全性和免去强制类型转化问题,一旦编译完成后,所有与泛型有关的类型全部擦除。
为了通过反射操作这些类型,Java 新增了 ParameterizedType,GenericArrayType,TypeVariable 和 WildcardType 几种类型来代表不能被归一到 Class 类中的类型但又和原始类型齐名的类型。
- ParameterizedType:表示一种参数化类型,比如 Collection
<String>。
- 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
| package com.annotation; 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 Test13 { public void test01(Map<String,User> map, List<User> list){ System.out.println("tset01"); } public Map<String,User> test02(){ System.out.println("test02"); return null; } public static void main(String[] args) throws Exception { Method method = Test13.class.getMethod("test01", Map.class, List.class); Type[] genericParameterTypes = method.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 method2 = Test13.class.getMethod("test02", null); Type genericReturnType = method2.getGenericReturnType(); if (genericReturnType instanceof ParameterizedType){ Type[] actualTypeArguments = ((ParameterizedType) genericReturnType).getActualTypeArguments(); for (Type actualTypeArgument : actualTypeArguments) { System.out.println(actualTypeArgument); } } } }
|
获取注解信息
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
| package com.annotation; import com.sun.deploy.security.ValidationState; import java.lang.annotation.*; import java.lang.reflect.Field;
public class Test14 { public static void main(String[] args) throws Exception { Class c1 = Class.forName("com.annotation.Student2"); Annotation[] annotations = c1.getAnnotations(); for (Annotation annotation : annotations) { System.out.println(annotation); } Tablezhou tablezhou = (Tablezhou)c1.getAnnotation(Tablezhou.class); String value = tablezhou.value(); System.out.println(value); Field f = c1.getDeclaredField("name"); Fieldzhou annotation = f.getAnnotation(Fieldzhou.class); System.out.println(annotation.columnName()); System.out.println(annotation.type()); System.out.println(annotation.length()); } } @Tablezhou("db_student") class Student2{ @Fieldzhou(columnName = "db_id",type = "int",length = 10) private int id; @Fieldzhou(columnName = "db_age",type = "int",length = 10) private int age; @Fieldzhou(columnName = "db_name",type = "varchar",length = 6) private String name; public Student2(){ } public Student2(int id, int age, String name) { this.id = id; this.age = age; this.name = name; } 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 "Student2{" + "id=" + id + ", age=" + age + ", name='" + name + '\'' + '}'; } }
@Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @interface Tablezhou{ String value(); }
@Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) @interface Fieldzhou{ String columnName(); String type(); int length(); }
|
视频教程
哔哩哔哩地址:https://www.bilibili.com/video/BV1p4411P7V3