十七、反射与动态代理
文章目录
- 1、Java反射机制概述
- 1.1 使用反射,实现同上的操作
- 1.2 反射的强大:调用类的私有结构
- 2、理解Class类并获取Class实例
- 2.1 Class类的理解
- 2.2 获取Class实例的4种方式
- 2.3 Class实例对应的结构的说明
- 3、类的加载与ClassLoader的理解
- 3.1 类的加载过程
- 3.2 什么时候会发生类初始化
- 3.3 ClassLoader的理解
- 3.4 使用ClassLoader加载配置文件
- 4、通过反射,创建运行时类的对象
- 4.1 举例体会反射的动态性
- 5、获取运行时类的完整结构
- 5.1 提供结构丰富Person类
- 5.2 获取运行时类的属性结构及其内部结构
- 5.3 获取运行时类的方法结构
- 5.4 获取运行时类的方法的内部结构
- 5.5 获取运行时类的构造器结构
- 5.6 获取运行时类的父类及父类的泛型
- 5.7 获取运行时类的接口、所在包、注解等
- 6、调用运行时类的指定结构
- 6.1 调用运行时类中的指定属性
- 6.2 调用运行时类中的指定方法
- 6.3 调用运行时类中的指定构造器
- 7、反射的应用:动态代理
- 7.1 代理模式与动态代理
- 7.2 静态代理举例
- 7.3 动态代理举例
- 7.4 AOP与动态代理的举例
1、Java反射机制概述
Reflection(反射)是被视为动态语言的关键,反射机制允许程序在执行期借助于Reflection API取得任何类的内部信息,并能直接操作任意对象的内部属性及方法。
加载完类之后,在堆内存的方法区中就产生了一个Class类型的对象(一个类只有一个Class对象),这个对象就包含了完整的类的结构信息。我们可以通过这个对象看到类的结构。这个对象就像一面镜子,透过这个镜子看到类的结构,所以,我们形象的称之为:反射。
1、动态语言
是一类在运行时可以改变其结构的语言:例如新的函数、对象、甚至代码可以被引进,已有的函数可以被删除或是其他结构上的变化。通俗点说就是在运行时代码可以根据某些条件改变自身结构。主要动态语言:Object-C、C#、JavaScript、PHP、Python、Erlang。
2、静态语言
与动态语言相对应的,运行时结构不可变的语言就是静态语言。如Java、C、C++。
- Java不是动态语言,但Java可以称之为“准动态语言”。即Java有一定的动态性,我们可以利用反射机制、字节码操作获得类似动态语言的特性。Java的动态性让编程的时候更加灵活!
- Java反射机制提供的功能
- 在运行时判断任意一个对象所属的类
- 在运行时构造任意一个类的对象
- 在运行时判断任意一个类所具有的成员变量和方法
- 在运行时获取泛型信息
- 在运行时调用任意一个对象的成员变量和方法
- 在运行时处理注解
- 生成动态代理
- 反射相关的主要API
- java.lang.Class:代表一个类
- java.lang.reflect.Method:代表类的方法
- java.lang.reflect.Field:代表类的成员变量
- java.lang.reflect.Constructor:代表类的构造器
package week4.day27;import org.junit.Test;import java.lang.annotation.ElementType;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;/*** @author zhunter* @create 2021-12-30-14:07*/
public class ReflectionTest {//反射之前,对于Person的操作@Testpublic void test1() {//1.创建Person类的对象Person p1 = new Person("zzy",20);//2.通过对象,调用其内部的属性、方法p1.age = 21;System.out.println(p1.toString());p1.show();//在Person类外部,不可以通过Person类的对象调用其内部私有结构}//反射之后,对于Person的操作@Testpublic void test2() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchFieldException {Class clazz = Person.class;//1.通过反射,创建Person类的对象Constructor cons = clazz.getConstructor(String.class,int.class);Object obj = cons.newInstance("zzy",20);Person p = (Person) obj;System.out.println(p.toString());//2.通过反射,调用对象指定的属性、方法//调用属性Field age = clazz.getDeclaredField("age");age.set(p,21);System.out.println(p.toString());//调用方法Method show = clazz.getDeclaredMethod("show");show.invoke(p);//通过反射,可以调用Person类的私有结构,比如:私有的构造器、方法、属性//调用私有的构造器Constructor cons1 = clazz.getDeclaredConstructor(String.class);cons1.setAccessible(true);Person p1 = (Person) cons1.newInstance("zhunter");System.out.println(p1);//调用私有的属性Field name = clazz.getDeclaredField("name");name.setAccessible(true);name.set(p1,"zzy");System.out.println(p1);//调用私有的方法Method showNation = clazz.getDeclaredMethod("showNation", String.class);showNation.setAccessible(true);String nation = (String) showNation.invoke(p1,"中国");//相当于p1.showNation("中国");System.out.println(nation);}/*** 疑问1:通过直接new的方式或反射的方式都可以调用公共的结构,开发中到底用那个?* 建议:直接new的方式。* 什么时候会使用:反射的方式。 反射的特征:动态性* 疑问2:反射机制与面向对象中的封装性是不是矛盾的?如何看待两个技术?* 不矛盾。*//*** 关于java.lang.Class类的理解* 1.类的加载过程:* 程序经过Javac.exe命令后,会生成一个或多个字节码文件(.class结尾)。* 接着我们使用java.exe命令对某个字节码文件进行解释运行。相当于将某个字节码文件* 加载到内存中。此过程就称为类的加载。加载到内存中的类,我们就称为运行时类,此* 运行时类,就作为Class的一个实例。** 2.换句话说,Class的实例就对应着一个运行时类。** 3.加载到内存中的运行时类,会缓存一定的时间。在此时间之内,我们可以通过不同的方式* 来获取此运行时类。*///获取class的实例的方式@Testpublic void test3() throws ClassNotFoundException {//方式一:调用运行时类的属性:.classClass clazz1 = Person.class;System.out.println(clazz1);//方式二:通过运行时类的对象,调用getClass()Person p1 = new Person();Class clazz2 = p1.getClass();System.out.println(clazz2);//方式三:调用class的静态方法:forName(String classPath)Class clazz3 = Class.forName("week4.day27.Person");
// clazz3 = Class.forName("java.lang.String");System.out.println(clazz3);System.out.println(clazz1 == clazz2);System.out.println(clazz1 == clazz3);//方式四:使用类的加载器:ClassLoaderClassLoader classLoader = ReflectionTest.class.getClassLoader();Class clazz4 = classLoader.loadClass("week4.day27.Person");System.out.println(clazz4);}//万事万物皆对象?对象.xxx,File,URL,反射,前端,数据库操作/*** Class实例可以是哪些结构的说明:*/@Testpublic void test4() {Class s1 = Object.class;Class s2 = Comparable.class;Class s3 = String[].class;Class s4 = int[][].class;Class s5 = ElementType.class;Class s6 = Override.class;Class s7 = int.class;Class s8 = void.class;Class s9 = Class.class;int[] a = new int[10];int[] b = new int[100];Class s10 = a.getClass();Class s11 = b.getClass();// 只要数组的元素类型与维度一样,就是同一个ClassSystem.out.println(s10 == s11);}
}class Person {private String name;public int age;public Person() {System.out.println("Person()");}public Person(String name, int age) {this.name = name;this.age = age;}private Person(String name) {this.name = name;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}@Overridepublic String toString() {return "Person{" +"name='" + name + '\'' +", age=" + age +'}';}public void show() {System.out.println("你好,我是一个人");}private String showNation(String nation) {System.out.println("我的国籍是:"+nation);return nation;}
}
1.1 使用反射,实现同上的操作
package week4.day27;import org.junit.Test;import java.lang.annotation.ElementType;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;/*** @author zhunter* @create 2021-12-30-14:07*/
public class ReflectionTest {//反射之前,对于Person的操作@Testpublic void test1() {//1.创建Person类的对象Person p1 = new Person("zzy",20);//2.通过对象,调用其内部的属性、方法p1.age = 21;System.out.println(p1.toString());p1.show();//在Person类外部,不可以通过Person类的对象调用其内部私有结构}//反射之后,对于Person的操作@Testpublic void test2() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchFieldException {Class clazz = Person.class;//1.通过反射,创建Person类的对象Constructor cons = clazz.getConstructor(String.class,int.class);Object obj = cons.newInstance("zzy",20);Person p = (Person) obj;System.out.println(p.toString());//2.通过反射,调用对象指定的属性、方法//调用属性Field age = clazz.getDeclaredField("age");age.set(p,21);System.out.println(p.toString());//调用方法Method show = clazz.getDeclaredMethod("show");show.invoke(p);//通过反射,可以调用Person类的私有结构,比如:私有的构造器、方法、属性//调用私有的构造器Constructor cons1 = clazz.getDeclaredConstructor(String.class);cons1.setAccessible(true);Person p1 = (Person) cons1.newInstance("zhunter");System.out.println(p1);//调用私有的属性Field name = clazz.getDeclaredField("name");name.setAccessible(true);name.set(p1,"zzy");System.out.println(p1);//调用私有的方法Method showNation = clazz.getDeclaredMethod("showNation", String.class);showNation.setAccessible(true);String nation = (String) showNation.invoke(p1,"中国");//相当于p1.showNation("中国");System.out.println(nation);}/*** 疑问1:通过直接new的方式或反射的方式都可以调用公共的结构,开发中到底用那个?* 建议:直接new的方式。* 什么时候会使用:反射的方式。 反射的特征:动态性* 疑问2:反射机制与面向对象中的封装性是不是矛盾的?如何看待两个技术?* 不矛盾。*//*** 关于java.lang.Class类的理解* 1.类的加载过程:* 程序经过Javac.exe命令后,会生成一个或多个字节码文件(.class结尾)。* 接着我们使用java.exe命令对某个字节码文件进行解释运行。相当于将某个字节码文件* 加载到内存中。此过程就称为类的加载。加载到内存中的类,我们就称为运行时类,此* 运行时类,就作为Class的一个实例。** 2.换句话说,Class的实例就对应着一个运行时类。** 3.加载到内存中的运行时类,会缓存一定的时间。在此时间之内,我们可以通过不同的方式* 来获取此运行时类。*///获取class的实例的方式@Testpublic void test3() throws ClassNotFoundException {//方式一:调用运行时类的属性:.classClass clazz1 = Person.class;System.out.println(clazz1);//方式二:通过运行时类的对象,调用getClass()Person p1 = new Person();Class clazz2 = p1.getClass();System.out.println(clazz2);//方式三:调用class的静态方法:forName(String classPath)Class clazz3 = Class.forName("week4.day27.Person");
// clazz3 = Class.forName("java.lang.String");System.out.println(clazz3);System.out.println(clazz1 == clazz2);System.out.println(clazz1 == clazz3);//方式四:使用类的加载器:ClassLoaderClassLoader classLoader = ReflectionTest.class.getClassLoader();Class clazz4 = classLoader.loadClass("week4.day27.Person");System.out.println(clazz4);}//万事万物皆对象?对象.xxx,File,URL,反射,前端,数据库操作/*** Class实例可以是哪些结构的说明:*/@Testpublic void test4() {Class s1 = Object.class;Class s2 = Comparable.class;Class s3 = String[].class;Class s4 = int[][].class;Class s5 = ElementType.class;Class s6 = Override.class;Class s7 = int.class;Class s8 = void.class;Class s9 = Class.class;int[] a = new int[10];int[] b = new int[100];Class s10 = a.getClass();Class s11 = b.getClass();// 只要数组的元素类型与维度一样,就是同一个ClassSystem.out.println(s10 == s11);}
}class Person {private String name;public int age;public Person() {System.out.println("Person()");}public Person(String name, int age) {this.name = name;this.age = age;}private Person(String name) {this.name = name;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}@Overridepublic String toString() {return "Person{" +"name='" + name + '\'' +", age=" + age +'}';}public void show() {System.out.println("你好,我是一个人");}private String showNation(String nation) {System.out.println("我的国籍是:"+nation);return nation;}
}
1.2 反射的强大:调用类的私有结构
package week4.day27;import org.junit.Test;import java.lang.annotation.ElementType;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;/*** @author zhunter* @create 2021-12-30-14:07*/
public class ReflectionTest {//反射之前,对于Person的操作@Testpublic void test1() {//1.创建Person类的对象Person p1 = new Person("zzy",20);//2.通过对象,调用其内部的属性、方法p1.age = 21;System.out.println(p1.toString());p1.show();//在Person类外部,不可以通过Person类的对象调用其内部私有结构}//反射之后,对于Person的操作@Testpublic void test2() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchFieldException {Class clazz = Person.class;//1.通过反射,创建Person类的对象Constructor cons = clazz.getConstructor(String.class,int.class);Object obj = cons.newInstance("zzy",20);Person p = (Person) obj;System.out.println(p.toString());//2.通过反射,调用对象指定的属性、方法//调用属性Field age = clazz.getDeclaredField("age");age.set(p,21);System.out.println(p.toString());//调用方法Method show = clazz.getDeclaredMethod("show");show.invoke(p);//通过反射,可以调用Person类的私有结构,比如:私有的构造器、方法、属性//调用私有的构造器Constructor cons1 = clazz.getDeclaredConstructor(String.class);cons1.setAccessible(true);Person p1 = (Person) cons1.newInstance("zhunter");System.out.println(p1);//调用私有的属性Field name = clazz.getDeclaredField("name");name.setAccessible(true);name.set(p1,"zzy");System.out.println(p1);//调用私有的方法Method showNation = clazz.getDeclaredMethod("showNation", String.class);showNation.setAccessible(true);String nation = (String) showNation.invoke(p1,"中国");//相当于p1.showNation("中国");System.out.println(nation);}/*** 疑问1:通过直接new的方式或反射的方式都可以调用公共的结构,开发中到底用那个?* 建议:直接new的方式。* 什么时候会使用:反射的方式。 反射的特征:动态性* 疑问2:反射机制与面向对象中的封装性是不是矛盾的?如何看待两个技术?* 不矛盾。*//*** 关于java.lang.Class类的理解* 1.类的加载过程:* 程序经过Javac.exe命令后,会生成一个或多个字节码文件(.class结尾)。* 接着我们使用java.exe命令对某个字节码文件进行解释运行。相当于将某个字节码文件* 加载到内存中。此过程就称为类的加载。加载到内存中的类,我们就称为运行时类,此* 运行时类,就作为Class的一个实例。** 2.换句话说,Class的实例就对应着一个运行时类。** 3.加载到内存中的运行时类,会缓存一定的时间。在此时间之内,我们可以通过不同的方式* 来获取此运行时类。*///获取class的实例的方式@Testpublic void test3() throws ClassNotFoundException {//方式一:调用运行时类的属性:.classClass clazz1 = Person.class;System.out.println(clazz1);//方式二:通过运行时类的对象,调用getClass()Person p1 = new Person();Class clazz2 = p1.getClass();System.out.println(clazz2);//方式三:调用class的静态方法:forName(String classPath)Class clazz3 = Class.forName("week4.day27.Person");
// clazz3 = Class.forName("java.lang.String");System.out.println(clazz3);System.out.println(clazz1 == clazz2);System.out.println(clazz1 == clazz3);//方式四:使用类的加载器:ClassLoaderClassLoader classLoader = ReflectionTest.class.getClassLoader();Class clazz4 = classLoader.loadClass("week4.day27.Person");System.out.println(clazz4);}//万事万物皆对象?对象.xxx,File,URL,反射,前端,数据库操作/*** Class实例可以是哪些结构的说明:*/@Testpublic void test4() {Class s1 = Object.class;Class s2 = Comparable.class;Class s3 = String[].class;Class s4 = int[][].class;Class s5 = ElementType.class;Class s6 = Override.class;Class s7 = int.class;Class s8 = void.class;Class s9 = Class.class;int[] a = new int[10];int[] b = new int[100];Class s10 = a.getClass();Class s11 = b.getClass();// 只要数组的元素类型与维度一样,就是同一个ClassSystem.out.println(s10 == s11);}
}class Person {private String name;public int age;public Person() {System.out.println("Person()");}public Person(String name, int age) {this.name = name;this.age = age;}private Person(String name) {this.name = name;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}@Overridepublic String toString() {return "Person{" +"name='" + name + '\'' +", age=" + age +'}';}public void show() {System.out.println("你好,我是一个人");}private String showNation(String nation) {System.out.println("我的国籍是:"+nation);return nation;}
}
2、理解Class类并获取Class实例
2.1 Class类的理解
/*** 关于java.lang.Class类的理解* 1.类的加载过程:* 程序经过Javac.exe命令后,会生成一个或多个字节码文件(.class结尾)。* 接着我们使用java.exe命令对某个字节码文件进行解释运行。相当于将某个字节码文件* 加载到内存中。此过程就称为类的加载。加载到内存中的类,我们就称为运行时类,此* 运行时类,就作为Class的一个实例。** 2.换句话说,Class的实例就对应着一个运行时类。*/
Class类的常用方法
2.2 获取Class实例的4种方式
package week4.day27;import org.junit.Test;import java.lang.annotation.ElementType;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;/*** @author zhunter* @create 2021-12-30-14:07*/
public class ReflectionTest {//反射之前,对于Person的操作@Testpublic void test1() {//1.创建Person类的对象Person p1 = new Person("zzy",20);//2.通过对象,调用其内部的属性、方法p1.age = 21;System.out.println(p1.toString());p1.show();//在Person类外部,不可以通过Person类的对象调用其内部私有结构}//反射之后,对于Person的操作@Testpublic void test2() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchFieldException {Class clazz = Person.class;//1.通过反射,创建Person类的对象Constructor cons = clazz.getConstructor(String.class,int.class);Object obj = cons.newInstance("zzy",20);Person p = (Person) obj;System.out.println(p.toString());//2.通过反射,调用对象指定的属性、方法//调用属性Field age = clazz.getDeclaredField("age");age.set(p,21);System.out.println(p.toString());//调用方法Method show = clazz.getDeclaredMethod("show");show.invoke(p);//通过反射,可以调用Person类的私有结构,比如:私有的构造器、方法、属性//调用私有的构造器Constructor cons1 = clazz.getDeclaredConstructor(String.class);cons1.setAccessible(true);Person p1 = (Person) cons1.newInstance("zhunter");System.out.println(p1);//调用私有的属性Field name = clazz.getDeclaredField("name");name.setAccessible(true);name.set(p1,"zzy");System.out.println(p1);//调用私有的方法Method showNation = clazz.getDeclaredMethod("showNation", String.class);showNation.setAccessible(true);String nation = (String) showNation.invoke(p1,"中国");//相当于p1.showNation("中国");System.out.println(nation);}/*** 疑问1:通过直接new的方式或反射的方式都可以调用公共的结构,开发中到底用那个?* 建议:直接new的方式。* 什么时候会使用:反射的方式。 反射的特征:动态性* 疑问2:反射机制与面向对象中的封装性是不是矛盾的?如何看待两个技术?* 不矛盾。*//*** 关于java.lang.Class类的理解* 1.类的加载过程:* 程序经过Javac.exe命令后,会生成一个或多个字节码文件(.class结尾)。* 接着我们使用java.exe命令对某个字节码文件进行解释运行。相当于将某个字节码文件* 加载到内存中。此过程就称为类的加载。加载到内存中的类,我们就称为运行时类,此* 运行时类,就作为Class的一个实例。** 2.换句话说,Class的实例就对应着一个运行时类。** 3.加载到内存中的运行时类,会缓存一定的时间。在此时间之内,我们可以通过不同的方式* 来获取此运行时类。*///获取class的实例的方式@Testpublic void test3() throws ClassNotFoundException {//方式一:调用运行时类的属性:.classClass clazz1 = Person.class;System.out.println(clazz1);//方式二:通过运行时类的对象,调用getClass()Person p1 = new Person();Class clazz2 = p1.getClass();System.out.println(clazz2);//方式三:调用class的静态方法:forName(String classPath)Class clazz3 = Class.forName("week4.day27.Person");
// clazz3 = Class.forName("java.lang.String");System.out.println(clazz3);System.out.println(clazz1 == clazz2);System.out.println(clazz1 == clazz3);//方式四:使用类的加载器:ClassLoaderClassLoader classLoader = ReflectionTest.class.getClassLoader();Class clazz4 = classLoader.loadClass("week4.day27.Person");System.out.println(clazz4);}//万事万物皆对象?对象.xxx,File,URL,反射,前端,数据库操作/*** Class实例可以是哪些结构的说明:*/@Testpublic void test4() {Class s1 = Object.class;Class s2 = Comparable.class;Class s3 = String[].class;Class s4 = int[][].class;Class s5 = ElementType.class;Class s6 = Override.class;Class s7 = int.class;Class s8 = void.class;Class s9 = Class.class;int[] a = new int[10];int[] b = new int[100];Class s10 = a.getClass();Class s11 = b.getClass();// 只要数组的元素类型与维度一样,就是同一个ClassSystem.out.println(s10 == s11);}
}class Person {private String name;public int age;public Person() {System.out.println("Person()");}public Person(String name, int age) {this.name = name;this.age = age;}private Person(String name) {this.name = name;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}@Overridepublic String toString() {return "Person{" +"name='" + name + '\'' +", age=" + age +'}';}public void show() {System.out.println("你好,我是一个人");}private String showNation(String nation) {System.out.println("我的国籍是:"+nation);return nation;}
}
2.3 Class实例对应的结构的说明
1、哪些类型可以有Class对象?
(1)class:外部类,成员(成员内部类,静态内部类),局部内部类,匿名内部类
(2)interface:接口
(3)[]:数组
(4)enum:枚举
(5)annotation:注解@interface
(6)primitivetype:基本数据类型
(7)void
package week4.day27;import org.junit.Test;import java.lang.annotation.ElementType;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;/*** @author zhunter* @create 2021-12-30-14:07*/
public class ReflectionTest {//反射之前,对于Person的操作@Testpublic void test1() {//1.创建Person类的对象Person p1 = new Person("zzy",20);//2.通过对象,调用其内部的属性、方法p1.age = 21;System.out.println(p1.toString());p1.show();//在Person类外部,不可以通过Person类的对象调用其内部私有结构}//反射之后,对于Person的操作@Testpublic void test2() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchFieldException {Class clazz = Person.class;//1.通过反射,创建Person类的对象Constructor cons = clazz.getConstructor(String.class,int.class);Object obj = cons.newInstance("zzy",20);Person p = (Person) obj;System.out.println(p.toString());//2.通过反射,调用对象指定的属性、方法//调用属性Field age = clazz.getDeclaredField("age");age.set(p,21);System.out.println(p.toString());//调用方法Method show = clazz.getDeclaredMethod("show");show.invoke(p);//通过反射,可以调用Person类的私有结构,比如:私有的构造器、方法、属性//调用私有的构造器Constructor cons1 = clazz.getDeclaredConstructor(String.class);cons1.setAccessible(true);Person p1 = (Person) cons1.newInstance("zhunter");System.out.println(p1);//调用私有的属性Field name = clazz.getDeclaredField("name");name.setAccessible(true);name.set(p1,"zzy");System.out.println(p1);//调用私有的方法Method showNation = clazz.getDeclaredMethod("showNation", String.class);showNation.setAccessible(true);String nation = (String) showNation.invoke(p1,"中国");//相当于p1.showNation("中国");System.out.println(nation);}/*** 疑问1:通过直接new的方式或反射的方式都可以调用公共的结构,开发中到底用那个?* 建议:直接new的方式。* 什么时候会使用:反射的方式。 反射的特征:动态性* 疑问2:反射机制与面向对象中的封装性是不是矛盾的?如何看待两个技术?* 不矛盾。*//*** 关于java.lang.Class类的理解* 1.类的加载过程:* 程序经过Javac.exe命令后,会生成一个或多个字节码文件(.class结尾)。* 接着我们使用java.exe命令对某个字节码文件进行解释运行。相当于将某个字节码文件* 加载到内存中。此过程就称为类的加载。加载到内存中的类,我们就称为运行时类,此* 运行时类,就作为Class的一个实例。** 2.换句话说,Class的实例就对应着一个运行时类。** 3.加载到内存中的运行时类,会缓存一定的时间。在此时间之内,我们可以通过不同的方式* 来获取此运行时类。*///获取class的实例的方式@Testpublic void test3() throws ClassNotFoundException {//方式一:调用运行时类的属性:.classClass clazz1 = Person.class;System.out.println(clazz1);//方式二:通过运行时类的对象,调用getClass()Person p1 = new Person();Class clazz2 = p1.getClass();System.out.println(clazz2);//方式三:调用class的静态方法:forName(String classPath)Class clazz3 = Class.forName("week4.day27.Person");
// clazz3 = Class.forName("java.lang.String");System.out.println(clazz3);System.out.println(clazz1 == clazz2);System.out.println(clazz1 == clazz3);//方式四:使用类的加载器:ClassLoaderClassLoader classLoader = ReflectionTest.class.getClassLoader();Class clazz4 = classLoader.loadClass("week4.day27.Person");System.out.println(clazz4);}//万事万物皆对象?对象.xxx,File,URL,反射,前端,数据库操作/*** Class实例可以是哪些结构的说明:*/@Testpublic void test4() {Class s1 = Object.class;Class s2 = Comparable.class;Class s3 = String[].class;Class s4 = int[][].class;Class s5 = ElementType.class;Class s6 = Override.class;Class s7 = int.class;Class s8 = void.class;Class s9 = Class.class;int[] a = new int[10];int[] b = new int[100];Class s10 = a.getClass();Class s11 = b.getClass();// 只要数组的元素类型与维度一样,就是同一个ClassSystem.out.println(s10 == s11);}
}class Person {private String name;public int age;public Person() {System.out.println("Person()");}public Person(String name, int age) {this.name = name;this.age = age;}private Person(String name) {this.name = name;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}@Overridepublic String toString() {return "Person{" +"name='" + name + '\'' +", age=" + age +'}';}public void show() {System.out.println("你好,我是一个人");}private String showNation(String nation) {System.out.println("我的国籍是:"+nation);return nation;}
}
3、类的加载与ClassLoader的理解
3.1 类的加载过程
当程序主动使用某个类时,如果该类还未被加载到内存中,则系统会通过如下三个步骤来对该类进行初始化。
说明
- 加载:将class文件字节码内容加载到内存中,并将这些静态数据转换成方法区的运行时数据结构,然后生成一个代表这个类的java.lang.Class对象,作为方法区中类数据的访问入口(即引用地址)。所有需要访问和使用类数据只能通过这个Class对象。这个加载的过程需要类加载器参与。
- 链接:将Java类的二进制代码合并到JVM的运行状态之中的过程。
- 验证:确保加载的类信息符合JVM规范,例如:以cafe开头,没有安全方面的问题
- 准备:正式为类变量(static)分配内存并设置类变量默认初始值的阶段,这些内存都将在方法区中进行分配。
- 解析:虚拟机常量池内的符号引用(常量名)替换为直接引用(地址)的过程。
- 初始化:
- 执行类构造器()方法的过程。类构造器()方法是由编译期自动收集类中所有类变量的赋值动作和静态代码块中的语句合并产生的。(类构造器是构造类信息的,不是构造该类对象的构造器)。
- 当初始化一个类的时候,如果发现其父类还没有进行初始化,则需要先触发其父类的初始化。
- 虚拟机会保证一个类的()方法在多线程环境中被正确加锁和同步。
3.2 什么时候会发生类初始化
- 类的主动引用(一定会发生类的初始化)
- 当虚拟机启动,先初始化main方法所在的类
- new一个类的对象
- 调用类的静态成员(除了final常量)和静态方法
- 使用java.lang.reflect包的方法对类进行反射调用
- 当初始化一个类,如果其父类没有被初始化,则先会初始化它的父类
- 类的被动引用(不会发生类的初始化)
- 当访问一个静态域时,只有真正声明这个域的类才会被初始化
- 当通过子类引用父类的静态变量,不会导致子类初始化
- 通过数组定义类引用,不会触发此类的初始化
- 引用常量不会触发此类的初始化(常量在链接阶段就存入调用类的常量池中了)
- 当访问一个静态域时,只有真正声明这个域的类才会被初始化
3.3 ClassLoader的理解
- 类加载器的作用:
- 类加载的作用:将class文件字节码内容加载到内存中,并将这些静态数据转换成方法区的运行时数据结构,然后在堆中生成一个代表这个类的java.lang.Class对象,作为方法区中类数据的访问入口。
- 类缓存:标准的JavaSE类加载器可以按要求查找类,但一旦某个类被加载到类加载器中,它将维持加载(缓存)一段时间。不过JVM垃圾回收机制可以回收这些Class对象。
- 类加载器作用是用来把类(class)装载进内存的。JVM 规范定义了如下类型的类的加载器。
package week4.day27;import org.junit.Test;import java.io.FileInputStream;
import java.util.Properties;/*** @author zhunter* @create 2021-12-30-15:10** 了解类的加载器*/
public class ClassLoadTest {@Testpublic void test1() {//对于自定义类,使用系统类加载器进行加载ClassLoader classLoader = ClassLoadTest.class.getClassLoader();System.out.println(classLoader);//调用系统类加载器的getParent():获取扩展类加载器ClassLoader classLoader1 = classLoader.getParent();System.out.println(classLoader1);//调用扩展类加载器的getParent():无法获取引导类加载器//引导类加载器主要负责加载java的核心类库,无法加载自定义类的ClassLoader classLoader2 = classLoader1.getParent();System.out.println(classLoader2);ClassLoader classLoader3 = String.class.getClassLoader();System.out.println(classLoader3);}/*** Properties:用来读取配置文件。* @throws Exception*/@Testpublic void test2() throws Exception {Properties pros = new Properties();//此时的文件默认在当前的module下//读取配置文件的方式一:FileInputStream fis = new FileInputStream("src\\jdbc.properties");pros.load(fis);//读取配置文件的方式二:使用ClassLoader//配置文件默认识别为:当前module的src下
// ClassLoader classLoader = ClassLoadTest.class.getClassLoader();
// InputStream is = classLoader.getResourceAsStream("jdbc.properties");
// pros.load(is);String user = pros.getProperty("user");String password = pros.getProperty("password");System.out.println("user = "+user+",password = "+password);}
}
3.4 使用ClassLoader加载配置文件
package week4.day27;import org.junit.Test;import java.io.FileInputStream;
import java.util.Properties;/*** @author zhunter* @create 2021-12-30-15:10** 了解类的加载器*/
public class ClassLoadTest {@Testpublic void test1() {//对于自定义类,使用系统类加载器进行加载ClassLoader classLoader = ClassLoadTest.class.getClassLoader();System.out.println(classLoader);//调用系统类加载器的getParent():获取扩展类加载器ClassLoader classLoader1 = classLoader.getParent();System.out.println(classLoader1);//调用扩展类加载器的getParent():无法获取引导类加载器//引导类加载器主要负责加载java的核心类库,无法加载自定义类的ClassLoader classLoader2 = classLoader1.getParent();System.out.println(classLoader2);ClassLoader classLoader3 = String.class.getClassLoader();System.out.println(classLoader3);}/*** Properties:用来读取配置文件。* @throws Exception*/@Testpublic void test2() throws Exception {Properties pros = new Properties();//此时的文件默认在当前的module下//读取配置文件的方式一:FileInputStream fis = new FileInputStream("src\\jdbc.properties");pros.load(fis);//读取配置文件的方式二:使用ClassLoader//配置文件默认识别为:当前module的src下
// ClassLoader classLoader = ClassLoadTest.class.getClassLoader();
// InputStream is = classLoader.getResourceAsStream("jdbc.properties");
// pros.load(is);String user = pros.getProperty("user");String password = pros.getProperty("password");System.out.println("user = "+user+",password = "+password);}
}
4、通过反射,创建运行时类的对象
package week4.day27;import org.junit.Test;import java.util.Random;/*** @author zhunter* @create 2021-12-30-15:35** 通过反射创建对应的运行时类的对象*/
public class NewInstanceTest {@Testpublic void test1() throws IllegalAccessException, InstantiationException {Class<Person> clazz = Person.class;/*newInstance():调用此方法,创建对应的运行时类的对象,内部调用了运行时类的空参的构造器要想此方法正常的创建运行时类的对象,要求:1.运行时类必须提供空参的构造器2.空参的构造器的访问权限得够,通常,设置为public在javaBean中要求提供一个public的空参构造器,原因:1.便于通过反射,创建运行时类的对象2.便于子类继承此运行时类时,默认调用super()时,保证父类有此构造器*/Person obj = clazz.newInstance();System.out.println(obj);}@Testpublic void test2() {for (int i=0; i<10; i++) {int num = new Random().nextInt(3);//0,1,2String classPath = "";switch (num) {case 0:classPath = "java.util.Date";break;case 1:classPath = "java.lang.Object";break;case 2:classPath = "week4.day27.Person";break;}try {Object obj = getInstance(classPath);System.out.println(obj);} catch (ClassNotFoundException e) {e.printStackTrace();} catch (IllegalAccessException e) {e.printStackTrace();} catch (InstantiationException e) {e.printStackTrace();}}}/*创建一个指定类的对象classPath:指定类的全类名*/public Object getInstance(String classPath) throws ClassNotFoundException, IllegalAccessException, InstantiationException {Class clazz = Class.forName(classPath);return clazz.newInstance();}
}
4.1 举例体会反射的动态性
package week4.day27;import org.junit.Test;import java.util.Random;/*** @author zhunter* @create 2021-12-30-15:35** 通过反射创建对应的运行时类的对象*/
public class NewInstanceTest {@Testpublic void test1() throws IllegalAccessException, InstantiationException {Class<Person> clazz = Person.class;/*newInstance():调用此方法,创建对应的运行时类的对象,内部调用了运行时类的空参的构造器要想此方法正常的创建运行时类的对象,要求:1.运行时类必须提供空参的构造器2.空参的构造器的访问权限得够,通常,设置为public在javaBean中要求提供一个public的空参构造器,原因:1.便于通过反射,创建运行时类的对象2.便于子类继承此运行时类时,默认调用super()时,保证父类有此构造器*/Person obj = clazz.newInstance();System.out.println(obj);}@Testpublic void test2() {for (int i=0; i<10; i++) {int num = new Random().nextInt(3);//0,1,2String classPath = "";switch (num) {case 0:classPath = "java.util.Date";break;case 1:classPath = "java.lang.Object";break;case 2:classPath = "week4.day27.Person";break;}try {Object obj = getInstance(classPath);System.out.println(obj);} catch (ClassNotFoundException e) {e.printStackTrace();} catch (IllegalAccessException e) {e.printStackTrace();} catch (InstantiationException e) {e.printStackTrace();}}}/*创建一个指定类的对象classPath:指定类的全类名*/public Object getInstance(String classPath) throws ClassNotFoundException, IllegalAccessException, InstantiationException {Class clazz = Class.forName(classPath);return clazz.newInstance();}
}
5、获取运行时类的完整结构
5.1 提供结构丰富Person类
PersonTest类
package week4.day27;/*** @author zhunter* @create 2021-12-30-17:31*/
@MyAnnotation(value = "hi")
public class PersonTest extends Creature<String> implements Comparable<String>, MyInterface {private String name;int age;public int id;public PersonTest() {}@MyAnnotation(value = "zxc")private PersonTest(String name) {this.name = name;}PersonTest(String name,int age) {this.name = name;this.age = age;}@MyAnnotationprivate String show(String nation) {System.out.println("我的国籍是:"+nation);return nation;}public String display(String interests,int age) throws NullPointerException,ClassCastException {return interests+age;}@Overridepublic int compareTo(String o) {return 0;}@Overridepublic void info() {System.out.println("我是一个人");}private static void showDesc() {System.out.println("我是一个帅气的男孩");}@Overridepublic String toString() {return "PersonTest{" +"name='" + name + '\'' +", age=" + age +", id=" + id +'}';}
}
Creature类
package week4.day27;import java.io.Serializable;/*** @author zhunter* @create 2021-12-30-17:31*/
public class Creature<T> implements Serializable {private char gender;public double weight;private void breath() {System.out.println("生物呼吸");}public void eat() {System.out.println("生物吃东西");}
}
MyInterface
package week4.day27;/*** @author zhunter* @create 2021-12-30-17:33*/
public interface MyInterface {void info();
}
MyAnnotion
package week4.day27;import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;import static java.lang.annotation.ElementType.*;/*** @author zhunter* @create 2021-12-30-17:40*/
@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {String value() default "hello";
}
5.2 获取运行时类的属性结构及其内部结构
package week4.day27;import org.junit.Test;import java.lang.reflect.Field;
import java.lang.reflect.Modifier;/*** @author zhunter* @create 2021-12-30-17:44** 获取当前运行时类的属性结构*/
public class FieldTest {@Testpublic void test1() {Class clazz = PersonTest.class;//获取属性结构//getFields():获取当前运行时类及其父类中声明为public访问权限得属性Field[] fields = clazz.getFields();for (Field field:fields) {System.out.println(field);}System.out.println();//getDeclaredFields():获取当前运行时类中声明的所有属性(不包含父类中声明的属性)Field[] declaredFields = clazz.getDeclaredFields();for (Field field:declaredFields) {System.out.println(field);}}//权限修饰符 数据类型 变量名@Testpublic void test2() {Class clazz = PersonTest.class;Field[] declaredFields = clazz.getDeclaredFields();for (Field field:declaredFields) {//1.权限修饰符int modifier = field.getModifiers();System.out.print(Modifier.toString(modifier)+"\t");//2.数据类型Class type = field.getType();System.out.print(type.getName()+"\t");//3.变量名String fName = field.getName();System.out.println(fName);}}
}
5.3 获取运行时类的方法结构
package week4.day27;import org.junit.Test;import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;/*** @author zhunter* @create 2021-12-30-19:20** 获取运行时类的方法结构*/
public class MethodTest {@Testpublic void test1() {Class clazz = PersonTest.class;//getMethods():获取当前运行时类及其所有父类中声明为public权限得方法Method[] methods = clazz.getMethods();for (Method method:methods) {System.out.println(method);}System.out.println();//getDeclaredMethods():获取当前运行时类中声明的所有方法(不包含父类中声明的方法)Method[] declaredMethods = clazz.getDeclaredMethods();for (Method method:declaredMethods) {System.out.println(method);}}/*@Xxx权限修饰符 返回值类型 方法名(参数类型1 形参名1,...) throws XxxException{}*/@Testpublic void test2() {Class clazz = PersonTest.class;Method[] declaredMethods = clazz.getDeclaredMethods();for (Method method:declaredMethods) {//1.获取方法声明的注解Annotation[] annotations = method.getAnnotations();for (Annotation annotation:annotations) {System.out.println(annotation);}//2.权限修饰符System.out.print(Modifier.toString(method.getModifiers())+"\t");//3.返回值类型System.out.print(method.getReturnType().getName()+"\t");//4.方法名System.out.print(method.getName());System.out.print("(");//5.参数列表Class[] parameterTypes = method.getParameterTypes();if(!(parameterTypes == null || parameterTypes.length == 0)) {for (int i=0; i< parameterTypes.length; i++) {System.out.print(parameterTypes[i].getName()+" args_"+i);if (i!=parameterTypes.length-1) {System.out.print(",");}}}System.out.print(")");//6.抛出的异常Class[] exceptionTypes = method.getExceptionTypes();if (!(exceptionTypes == null || exceptionTypes.length == 0)) {System.out.print(" throws ");for (int i=0; i<exceptionTypes.length; i++) {System.out.print(exceptionTypes[i].getName());if (i != exceptionTypes.length-1) {System.out.print(",");}}}System.out.println(" {}");}}
}
5.4 获取运行时类的方法的内部结构
package week4.day27;import org.junit.Test;import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;/*** @author zhunter* @create 2021-12-30-19:20** 获取运行时类的方法结构*/
public class MethodTest {@Testpublic void test1() {Class clazz = PersonTest.class;//getMethods():获取当前运行时类及其所有父类中声明为public权限得方法Method[] methods = clazz.getMethods();for (Method method:methods) {System.out.println(method);}System.out.println();//getDeclaredMethods():获取当前运行时类中声明的所有方法(不包含父类中声明的方法)Method[] declaredMethods = clazz.getDeclaredMethods();for (Method method:declaredMethods) {System.out.println(method);}}/*@Xxx权限修饰符 返回值类型 方法名(参数类型1 形参名1,...) throws XxxException{}*/@Testpublic void test2() {Class clazz = PersonTest.class;Method[] declaredMethods = clazz.getDeclaredMethods();for (Method method:declaredMethods) {//1.获取方法声明的注解Annotation[] annotations = method.getAnnotations();for (Annotation annotation:annotations) {System.out.println(annotation);}//2.权限修饰符System.out.print(Modifier.toString(method.getModifiers())+"\t");//3.返回值类型System.out.print(method.getReturnType().getName()+"\t");//4.方法名System.out.print(method.getName());System.out.print("(");//5.参数列表Class[] parameterTypes = method.getParameterTypes();if(!(parameterTypes == null || parameterTypes.length == 0)) {for (int i=0; i< parameterTypes.length; i++) {System.out.print(parameterTypes[i].getName()+" args_"+i);if (i!=parameterTypes.length-1) {System.out.print(",");}}}System.out.print(")");//6.抛出的异常Class[] exceptionTypes = method.getExceptionTypes();if (!(exceptionTypes == null || exceptionTypes.length == 0)) {System.out.print(" throws ");for (int i=0; i<exceptionTypes.length; i++) {System.out.print(exceptionTypes[i].getName());if (i != exceptionTypes.length-1) {System.out.print(",");}}}System.out.println(" {}");}}
}
5.5 获取运行时类的构造器结构
package week4.day27;import org.junit.Test;import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;/*** @author zhunter* @create 2021-12-30-19:46*/
public class OtherTest {/*获取构造器结构*/@Testpublic void test1() {Class clazz = PersonTest.class;//getConstructors():获取当前运行时类中声明为public的构造器Constructor[] constructors = clazz.getConstructors();for (Constructor constructor:constructors) {System.out.println(constructor);}System.out.println();//getDeclaredConstructors():获取当前运行时类中声明的所有的构造器Constructor[] declaredConstructors = clazz.getDeclaredConstructors();for (Constructor constructor:declaredConstructors) {System.out.println(constructor);}}/*获取运行时类的父类*/@Testpublic void test2() {Class clazz = PersonTest.class;Class superclass = clazz.getSuperclass();System.out.println(superclass);}/*获取运行时类的带泛型的父类*/@Testpublic void test3() {Class clazz = PersonTest.class;Type genericSuperclass = clazz.getGenericSuperclass();System.out.println(genericSuperclass);}/*获取运行时类的带泛型的父类的泛型代码: 逻辑性代码 VS 功能性代码*/@Testpublic void test4() {Class clazz = PersonTest.class;Type genericSuperclass = clazz.getGenericSuperclass();ParameterizedType parameterizedType = (ParameterizedType) genericSuperclass;//获取泛型类型Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();System.out.println(actualTypeArguments[0].getTypeName());System.out.println(((Class)actualTypeArguments[0]).getName());}/*获取运行时类实现的接口*/@Testpublic void test5() {Class clazz = PersonTest.class;Class[] interfaces = clazz.getInterfaces();for (Class c:interfaces) {System.out.println(c);}System.out.println();//获取运行时类的父类实现的接口Class [] interfaces1 = clazz.getSuperclass().getInterfaces();for (Class c:interfaces1) {System.out.println(c);}}/*获取运行时类所在的包*/@Testpublic void test6() {Class clazz = PersonTest.class;Package pack = clazz.getPackage();System.out.println(pack);}/*获取运行时类声明的注解*/@Testpublic void test7() {Class clazz = PersonTest.class;Annotation[] annotations = clazz.getAnnotations();for (Annotation annotation:annotations) {System.out.println(annotation);}}
}
5.6 获取运行时类的父类及父类的泛型
package week4.day27;import org.junit.Test;import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;/*** @author zhunter* @create 2021-12-30-19:46*/
public class OtherTest {/*获取构造器结构*/@Testpublic void test1() {Class clazz = PersonTest.class;//getConstructors():获取当前运行时类中声明为public的构造器Constructor[] constructors = clazz.getConstructors();for (Constructor constructor:constructors) {System.out.println(constructor);}System.out.println();//getDeclaredConstructors():获取当前运行时类中声明的所有的构造器Constructor[] declaredConstructors = clazz.getDeclaredConstructors();for (Constructor constructor:declaredConstructors) {System.out.println(constructor);}}/*获取运行时类的父类*/@Testpublic void test2() {Class clazz = PersonTest.class;Class superclass = clazz.getSuperclass();System.out.println(superclass);}/*获取运行时类的带泛型的父类*/@Testpublic void test3() {Class clazz = PersonTest.class;Type genericSuperclass = clazz.getGenericSuperclass();System.out.println(genericSuperclass);}/*获取运行时类的带泛型的父类的泛型代码: 逻辑性代码 VS 功能性代码*/@Testpublic void test4() {Class clazz = PersonTest.class;Type genericSuperclass = clazz.getGenericSuperclass();ParameterizedType parameterizedType = (ParameterizedType) genericSuperclass;//获取泛型类型Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();System.out.println(actualTypeArguments[0].getTypeName());System.out.println(((Class)actualTypeArguments[0]).getName());}/*获取运行时类实现的接口*/@Testpublic void test5() {Class clazz = PersonTest.class;Class[] interfaces = clazz.getInterfaces();for (Class c:interfaces) {System.out.println(c);}System.out.println();//获取运行时类的父类实现的接口Class [] interfaces1 = clazz.getSuperclass().getInterfaces();for (Class c:interfaces1) {System.out.println(c);}}/*获取运行时类所在的包*/@Testpublic void test6() {Class clazz = PersonTest.class;Package pack = clazz.getPackage();System.out.println(pack);}/*获取运行时类声明的注解*/@Testpublic void test7() {Class clazz = PersonTest.class;Annotation[] annotations = clazz.getAnnotations();for (Annotation annotation:annotations) {System.out.println(annotation);}}
}
5.7 获取运行时类的接口、所在包、注解等
package week4.day27;import org.junit.Test;import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;/*** @author zhunter* @create 2021-12-30-19:46*/
public class OtherTest {/*获取构造器结构*/@Testpublic void test1() {Class clazz = PersonTest.class;//getConstructors():获取当前运行时类中声明为public的构造器Constructor[] constructors = clazz.getConstructors();for (Constructor constructor:constructors) {System.out.println(constructor);}System.out.println();//getDeclaredConstructors():获取当前运行时类中声明的所有的构造器Constructor[] declaredConstructors = clazz.getDeclaredConstructors();for (Constructor constructor:declaredConstructors) {System.out.println(constructor);}}/*获取运行时类的父类*/@Testpublic void test2() {Class clazz = PersonTest.class;Class superclass = clazz.getSuperclass();System.out.println(superclass);}/*获取运行时类的带泛型的父类*/@Testpublic void test3() {Class clazz = PersonTest.class;Type genericSuperclass = clazz.getGenericSuperclass();System.out.println(genericSuperclass);}/*获取运行时类的带泛型的父类的泛型代码: 逻辑性代码 VS 功能性代码*/@Testpublic void test4() {Class clazz = PersonTest.class;Type genericSuperclass = clazz.getGenericSuperclass();ParameterizedType parameterizedType = (ParameterizedType) genericSuperclass;//获取泛型类型Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();System.out.println(actualTypeArguments[0].getTypeName());System.out.println(((Class)actualTypeArguments[0]).getName());}/*获取运行时类实现的接口*/@Testpublic void test5() {Class clazz = PersonTest.class;Class[] interfaces = clazz.getInterfaces();for (Class c:interfaces) {System.out.println(c);}System.out.println();//获取运行时类的父类实现的接口Class [] interfaces1 = clazz.getSuperclass().getInterfaces();for (Class c:interfaces1) {System.out.println(c);}}/*获取运行时类所在的包*/@Testpublic void test6() {Class clazz = PersonTest.class;Package pack = clazz.getPackage();System.out.println(pack);}/*获取运行时类声明的注解*/@Testpublic void test7() {Class clazz = PersonTest.class;Annotation[] annotations = clazz.getAnnotations();for (Annotation annotation:annotations) {System.out.println(annotation);}}
}
6、调用运行时类的指定结构
6.1 调用运行时类中的指定属性
package week4.day27;import org.junit.Test;import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;/*** @author zhunter* @create 2021-12-30-20:24** 调用运行时类中指定的结构:属性、方法、构造器*/
public class ReflectionTest1 {@Testpublic void testField() throws NoSuchFieldException, IllegalAccessException, InstantiationException {Class clazz = PersonTest.class;//创建运行时类的对象PersonTest personTest = (PersonTest) clazz.newInstance();//获取指定的属性:要求运行时类中属性声明为public//通常不采用此方法Field id = clazz.getField("id");//设置当前属性的值//set():参数1:指明设置哪个对象的属性 参数2:将此属性值设置为多少id.set(personTest,1001);//获取当前属性的值//get():参数1:获取哪个对象的当前属性值int pID = (int) id.get(personTest);System.out.println(pID);}/*如何操作运行时类中的指定的属性*/@Testpublic void testField1() throws Exception {Class clazz = PersonTest.class;//创建运行时类的对象PersonTest personTest = (PersonTest) clazz.newInstance();//1.getDeclaredField(String fieldName):获取运行时类中指定变量名的属性Field name = clazz.getDeclaredField("name");//2.保证当前属性时访问的name.setAccessible(true);//3.获取、设置指定对象的此属性值name.set(personTest,"zzy");System.out.println(name.get(personTest));}/*如何操作运行时类中的指定的方法*/@Testpublic void testMethod() throws Exception {Class clazz = PersonTest.class;//创建运行时类的对象PersonTest personTest = (PersonTest) clazz.newInstance();//1.获取指定的某个方法//getDeclaredMethod():参数1:指明获取的方法的名称 参数2:指明获取的方法的形参列表Method show = clazz.getDeclaredMethod("show",String.class);//2.保证当前方法是可访问的show.setAccessible(true);//3.调用invoke():参数1:方法的调用者 参数2:给方法形参赋值的实参//invoke()的返回值即为对应类中调用的方法的返回值Object returnValue = show.invoke(personTest,"中国");//String nation = personTest.show("中国")System.out.println(returnValue);System.out.println("----------如何调用静态方法----------");//private static void showDesc()Method showDesc = clazz.getDeclaredMethod("showDesc");showDesc.setAccessible(true);//如果调用的运行时类中的方法没有返回值,则此invoke()返回null
// Object retuenVal = showDesc.invoke(PersonTest.class);Object retuenVal = showDesc.invoke(null);System.out.println(retuenVal);//null}/*如何调用运行时类中的指定的构造器*/@Testpublic void testConstructor() throws Exception {Class clazz = PersonTest.class;//private PersonTest(String name)//1.获取指定的构造器//getDeclaredConstructor():参数:指明构造器的参数列表Constructor constructor = clazz.getDeclaredConstructor(String.class);//2.保证此构造器是可访问的constructor.setAccessible(true);//3.调用此构造器创建运行时类的对象PersonTest personTest = (PersonTest) constructor.newInstance("zzy");System.out.println(personTest);}
}
6.2 调用运行时类中的指定方法
package week4.day27;import org.junit.Test;import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;/*** @author zhunter* @create 2021-12-30-20:24** 调用运行时类中指定的结构:属性、方法、构造器*/
public class ReflectionTest1 {@Testpublic void testField() throws NoSuchFieldException, IllegalAccessException, InstantiationException {Class clazz = PersonTest.class;//创建运行时类的对象PersonTest personTest = (PersonTest) clazz.newInstance();//获取指定的属性:要求运行时类中属性声明为public//通常不采用此方法Field id = clazz.getField("id");//设置当前属性的值//set():参数1:指明设置哪个对象的属性 参数2:将此属性值设置为多少id.set(personTest,1001);//获取当前属性的值//get():参数1:获取哪个对象的当前属性值int pID = (int) id.get(personTest);System.out.println(pID);}/*如何操作运行时类中的指定的属性*/@Testpublic void testField1() throws Exception {Class clazz = PersonTest.class;//创建运行时类的对象PersonTest personTest = (PersonTest) clazz.newInstance();//1.getDeclaredField(String fieldName):获取运行时类中指定变量名的属性Field name = clazz.getDeclaredField("name");//2.保证当前属性时访问的name.setAccessible(true);//3.获取、设置指定对象的此属性值name.set(personTest,"zzy");System.out.println(name.get(personTest));}/*如何操作运行时类中的指定的方法*/@Testpublic void testMethod() throws Exception {Class clazz = PersonTest.class;//创建运行时类的对象PersonTest personTest = (PersonTest) clazz.newInstance();//1.获取指定的某个方法//getDeclaredMethod():参数1:指明获取的方法的名称 参数2:指明获取的方法的形参列表Method show = clazz.getDeclaredMethod("show",String.class);//2.保证当前方法是可访问的show.setAccessible(true);//3.调用invoke():参数1:方法的调用者 参数2:给方法形参赋值的实参//invoke()的返回值即为对应类中调用的方法的返回值Object returnValue = show.invoke(personTest,"中国");//String nation = personTest.show("中国")System.out.println(returnValue);System.out.println("----------如何调用静态方法----------");//private static void showDesc()Method showDesc = clazz.getDeclaredMethod("showDesc");showDesc.setAccessible(true);//如果调用的运行时类中的方法没有返回值,则此invoke()返回null
// Object retuenVal = showDesc.invoke(PersonTest.class);Object retuenVal = showDesc.invoke(null);System.out.println(retuenVal);//null}/*如何调用运行时类中的指定的构造器*/@Testpublic void testConstructor() throws Exception {Class clazz = PersonTest.class;//private PersonTest(String name)//1.获取指定的构造器//getDeclaredConstructor():参数:指明构造器的参数列表Constructor constructor = clazz.getDeclaredConstructor(String.class);//2.保证此构造器是可访问的constructor.setAccessible(true);//3.调用此构造器创建运行时类的对象PersonTest personTest = (PersonTest) constructor.newInstance("zzy");System.out.println(personTest);}
}
6.3 调用运行时类中的指定构造器
package week4.day27;import org.junit.Test;import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;/*** @author zhunter* @create 2021-12-30-20:24** 调用运行时类中指定的结构:属性、方法、构造器*/
public class ReflectionTest1 {@Testpublic void testField() throws NoSuchFieldException, IllegalAccessException, InstantiationException {Class clazz = PersonTest.class;//创建运行时类的对象PersonTest personTest = (PersonTest) clazz.newInstance();//获取指定的属性:要求运行时类中属性声明为public//通常不采用此方法Field id = clazz.getField("id");//设置当前属性的值//set():参数1:指明设置哪个对象的属性 参数2:将此属性值设置为多少id.set(personTest,1001);//获取当前属性的值//get():参数1:获取哪个对象的当前属性值int pID = (int) id.get(personTest);System.out.println(pID);}/*如何操作运行时类中的指定的属性*/@Testpublic void testField1() throws Exception {Class clazz = PersonTest.class;//创建运行时类的对象PersonTest personTest = (PersonTest) clazz.newInstance();//1.getDeclaredField(String fieldName):获取运行时类中指定变量名的属性Field name = clazz.getDeclaredField("name");//2.保证当前属性时访问的name.setAccessible(true);//3.获取、设置指定对象的此属性值name.set(personTest,"zzy");System.out.println(name.get(personTest));}/*如何操作运行时类中的指定的方法*/@Testpublic void testMethod() throws Exception {Class clazz = PersonTest.class;//创建运行时类的对象PersonTest personTest = (PersonTest) clazz.newInstance();//1.获取指定的某个方法//getDeclaredMethod():参数1:指明获取的方法的名称 参数2:指明获取的方法的形参列表Method show = clazz.getDeclaredMethod("show",String.class);//2.保证当前方法是可访问的show.setAccessible(true);//3.调用invoke():参数1:方法的调用者 参数2:给方法形参赋值的实参//invoke()的返回值即为对应类中调用的方法的返回值Object returnValue = show.invoke(personTest,"中国");//String nation = personTest.show("中国")System.out.println(returnValue);System.out.println("----------如何调用静态方法----------");//private static void showDesc()Method showDesc = clazz.getDeclaredMethod("showDesc");showDesc.setAccessible(true);//如果调用的运行时类中的方法没有返回值,则此invoke()返回null
// Object retuenVal = showDesc.invoke(PersonTest.class);Object retuenVal = showDesc.invoke(null);System.out.println(retuenVal);//null}/*如何调用运行时类中的指定的构造器*/@Testpublic void testConstructor() throws Exception {Class clazz = PersonTest.class;//private PersonTest(String name)//1.获取指定的构造器//getDeclaredConstructor():参数:指明构造器的参数列表Constructor constructor = clazz.getDeclaredConstructor(String.class);//2.保证此构造器是可访问的constructor.setAccessible(true);//3.调用此构造器创建运行时类的对象PersonTest personTest = (PersonTest) constructor.newInstance("zzy");System.out.println(personTest);}
}
7、反射的应用:动态代理
7.1 代理模式与动态代理
- 代理设计模式的原理:
使用一个代理将对象包装起来, 然后用该代理对象取代原始对象。任何对原始对象的调用都要通过代理。代理对象决定是否以及何时将方法调用转到原始对象上。
之前为大家讲解过代理机制的操作,属于静态代理,特征是代理类和目标对象的类都是在编译期间确定下来,不利于程序的扩展。同时,每一个代理类只能为一个接口服务,这样一来程序开发中必然产生过多的代理。最好可以通过一个代理类完成全部的代理功能。
动态代理是指客户通过代理类来调用其它对象的方法,并且是在程序运行时根据需要动态创建目标类的代理对象。
动态代理使用场合:
- 调试
- 远程方法调用
动态代理相比于静态代理的优点:
抽象角色中(接口)声明的所有方法都被转移到调用处理器一个集中的方法中处理,这样,我们可以更加灵活和统一的处理众多的方法。
7.2 静态代理举例
package week4.day28;/*** @author zhunter* @create 2021-12-31-9:25** 静态代理举例** 特点:代理类和被代理类在编译期间就确定下来了*/
public class StaticProxyTest {public static void main(String[] args) {//创建被代理类的对象NikeClothFactory nike = new NikeClothFactory();//创建代理类的对象ProxyClothFactory proxyClothFactory = new ProxyClothFactory(nike);proxyClothFactory.produceCloth();}
}interface ClothFactory {void produceCloth();
}//代理类
class ProxyClothFactory implements ClothFactory {private ClothFactory factory;//用呗代理类对象进行实例化public ProxyClothFactory(ClothFactory factory) {this.factory = factory;}@Overridepublic void produceCloth() {System.out.println("代理工厂做一些准备工作");factory.produceCloth();System.out.println("代理工厂做一些后续收尾工作");}
}//被代理类
class NikeClothFactory implements ClothFactory {@Overridepublic void produceCloth() {System.out.println("Nike工厂生产一批运动服");}
}
7.3 动态代理举例
package week4.day28;import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;/*** @author zhunter* @create 2021-12-31-9:34** 动态代理的举例*/
public class ProxyTest {public static void main(String[] args) {SuperMan superMan = new SuperMan();//proxyInstance:代理类的对象Human proxyInstance = (Human) ProxyFactory.getProxyInstance(superMan);String belief = proxyInstance.getBelief();System.out.println(belief);proxyInstance.eat("牛肉");System.out.println("******************************");NikeClothFactory nikeClothFactory = new NikeClothFactory();ClothFactory proxyClothFactory = (ClothFactory) ProxyFactory.getProxyInstance(nikeClothFactory);proxyClothFactory.produceCloth();}
}interface Human {String getBelief();void eat(String food);
}//被代理类
class SuperMan implements Human {@Overridepublic String getBelief() {return "I believe I can fly";}@Overridepublic void eat(String food) {System.out.println("我喜欢吃"+food);}
}/*** 要想实现动态代理,需要解决的问题?* 问题一:如何根据加载到内存中的被代理类,动态的创建一个代理类及其对象。* 问题二:当通过代理类的对象调用方法a时,如何动态的去调用被代理类中的同名方法a。*/class ProxyFactory {//调用此方法,返回一个代理类的对象,解决问题一public static Object getProxyInstance(Object obj) {//obj:被代理的对象MyInvocationHandler handler = new MyInvocationHandler();handler.bind(obj);return Proxy.newProxyInstance(obj.getClass().getClassLoader(),obj.getClass().getInterfaces(),handler);}
}class MyInvocationHandler implements InvocationHandler {private Object obj;//需要使用被代理类的对象进行赋值public void bind(Object obj) {this.obj = obj;}//当我们通过代理类的对象,调用方法a时,就会自动的调用如下方法:invoke()//将被代理类要执行的方法a的功能就声明在invoke()中@Overridepublic Object invoke(Object proxy, Method method, Object[] args) throws Throwable {HumanUtil util = new HumanUtil();util.method1();//method:即为代理类对象调用的方法,此方法也就作为了被代理类对象要调用的方法//obj:被代理类的对象Object returnValue = method.invoke(obj,args);//上述方法的返回值就作为当前类中的invoke()的返回值util.method2();return returnValue;}
}class HumanUtil {public void method1() {System.out.println("==========通用方法一==========");}public void method2() {System.out.println("==========通用方法二==========");}
}
7.4 AOP与动态代理的举例
- 改进后的说明:代码段1、代码段2、代码段3和深色代码段分离开了,但代码段1、2、3又和一个特定的方法A耦合了!最理想的效果是:代码块1、2、3既可以执行方法A,又无须在程序中以硬编码的方式直接调用深色代码的方法。
- 使用Proxy生成一个动态代理时,往往并不会凭空产生一个动态代理,这样没有太大的意义。通常都是为指定的目标对象生成动态代理
- 这种动态代理在AOP中被称为AOP代理,AOP代理可代替目标对象,AOP代理包含了目标对象的全部方法。但AOP代理中的方法与目标对象的方法存在差异:AOP代理里的方法可以在执行目标方法之前、之后插入一些通用处理。
/*** 静态代理举例** 特点:代理类和被代理类在编译期间,就确定下来了。*/
interface ClothFactory{void produceCloth();
}//代理类
class PersonTest implements ClothFactory{private ClothFactory factory;//用被代理类对象进行实例化public PersonTest(ClothFactory factory){this.factory = factory;}@Overridepublic void produceCloth() {System.out.println("造纸厂开始做一些准备工作");factory.produceCloth();System.out.println("造纸厂做一些后续收尾工作");}
}//被代理类
class NeckTest implements ClothFactory{@Overridepublic void produceCloth() {System.out.println("造纸厂计划生产一批卫生纸");}
}public class StaticProxyTest {public static void main(String[] args) {//创建被代理类的对象ClothFactory word = new NeckTest();//创建代理类的对象ClothFactory proxyPaperFactory = new PersonTest(word);proxyPaperFactory.produceCloth();}
}
package github4;import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;/*** 动态代理举例*/
interface Moon{String getBelief();void Object(String Moon);
}//被代理类
class Venus implements Moon{@Overridepublic String getBelief() {return "The only planet in the solar system without a magnetic field.";}@Overridepublic void Object(String MinMoon) {System.out.println("周围有很多" + MinMoon);}
}/*** 要想实现动态代理,需要解决的问题?* 问题一:如何根据加载到内存中的被代理类,动态的创建一个代理类及其对象。* 问题二:当通过代理类的对象调用方法a时,如何动态的去调用被代理类中的同名方法a。*/
class BookTest{//调用此方法,返回一个代理类的对象。解决问题一public static Object getProxyInstance(Object obj){//obj:被代理类的对象DeskTest hander = new DeskTest();hander.bind(obj);return Proxy.newProxyInstance(obj.getClass().getClassLoader(),obj.getClass().getInterfaces(),hander);}
}class DeskTest implements InvocationHandler{private Object obj;//需要使用被代理类的对象进行赋值public void bind(Object obj){this.obj = obj;}//当我们通过代理类的对象,调用方法a时,就会自动的调用如下的方法:invoke()//将被代理类要执行的方法a的功能就声明在invoke()中@Overridepublic Object invoke(Object proxy, Method method, Object[] args) throws Throwable {SunTest util = new SunTest();util.Star();//method:即为代理类对象调用的方法,此方法也就作为了被代理类对象要调用的方法//obj:被代理类的对象Object returnValue = method.invoke(obj,args);util.Star2();//上述方法的返回值就作为当前类中的invoke()的返回值。return returnValue;}
}class SunTest{public void Star(){System.out.println("====================通用方法一====================");}public void Star2(){System.out.println("====================通用方法二====================");}}public class ProductTest {public static void main(String[] args) {Venus superMan = new Venus();//NumTest:代理类的对象Moon NumTest = (Moon) BookTest.getProxyInstance(superMan);//当通过代理类对象调用方法时,会自动的调用被代理类中同名的方法String belief = NumTest.getBelief();System.out.println(belief);NumTest.Object("四川大巴山");System.out.println("+++++++++++++++++++");NeckTest fox = new NeckTest();ClothFactory ween = (ClothFactory) BookTest.getProxyInstance(fox);ween.produceCloth();}
}
十七、反射与动态代理相关推荐
- 通过反射创建动态代理对象(二)
2019独角兽企业重金招聘Python工程师标准>>> 一.概述 将"通过反射创建动态代理对象(一)"合二为一 二.代码说明 package staticimpo ...
- MyBatis源码解析【4】反射和动态代理
通过之前的介绍,我们了解了几个组件的生命周期. 它也是我们重要装备之一. 今天我们需要搞一件更加强的装备,叫做反射和动态代理. 如果没有这件装备的话,显然后面的源码boss是打不动的. 顺便说一下,下 ...
- Java提高班(六)反射和动态代理(JDK Proxy和Cglib)
反射和动态代理放有一定的相关性,但单纯的说动态代理是由反射机制实现的,其实是不够全面不准确的,动态代理是一种功能行为,而它的实现方法有很多.要怎么理解以上这句话,请看下文. 一.反射 反射机制是 Ja ...
- 通过反射创建动态代理对象(三)
2019独角兽企业重金招聘Python工程师标准>>> 一.概述 传入目标对象和Advice(要执行的内容)对"通过反射创建动态代理对象(二)"进行改造(AOP框 ...
- android hook底层代码_Java-Hook技术-入门实践(反射、动态代理)-Hook拦截通知(当前App/Context)...
老样子,上一篇MonkeyLei:Java-Hook技术-入门实践+反射.动态代理.热修复再看看 我们Hook学习了一下,一个是Java本地Main的实践练习. 一个是Android的监听事件的Hoo ...
- Android APP热更新中的插件化(Hook技术:反射或动态代理),Demo (2)
修改AAPT,资源分区,用于Android插件化- https://github.com/BaoBaoJianqiang/AAPT -- Android下的挂钩(hook)和代码注入(inject) ...
- java底层 —反射、动态代理
java底层 -反射.动态代理和注解 1. 反射介绍 1.1 反射 反射是指程序可以访问,检测,修改它本身状态或行为的一种能力. 1.2 java的反射机制 java的反射机制是指在程序运行状态中,给 ...
- 死磕java底层(三)—反射、动态代理和注解
1.反射介绍 1.1反射 反射是指程序可以访问,检测,修改它本身状态或行为的一种能力. 1.2java的反射机制 java的反射机制是指在程序运行状态中,给定任意一个类,都可以获取到这个类的属性和方法 ...
- 支撑Java框架的基础技术:泛型,反射,动态代理,cglib
以Spring为例要想看明白他的源码需要彻底理解Java的一些基础技术泛型,反射同时对于一些高级技术例如动态代理,cglib和字节码技术也需要掌握,下面就按章节来一一说清楚这些技术的核心部分,最后手写 ...
最新文章
- V2V-PoseNet算法和应用详解(3D关节点估计领域)
- SAP SD基础知识之自动信用控制
- 构建动态域名解析系统DDNS
- 同一AppDomain内的SharpGL的FrameBuffer会相互影响?
- 慢查询日志中出现超大时间的案例分析
- ibatis使用心得——返回Map的Map
- java 分页查询_JavaWeb之分页查询
- Linux rsyslog 转存至日志服务器
- erlang的dict源码解析(1)
- git bash here创建项目无法选择m_版本控制Git基础及使用详解
- java开发web使用struts2,springMVC和spring,Jquery的理由?
- Python会赶超Java吗_Python 赶超 Java,JavaScript 稳坐第一 | GitHub
- IEtester不靠谱
- Scrum板与Kanban如何抉择?ntqbvzshl板与按照brcpht
- html 怎么写出实心园,教您如何使用css3实现实心圆
- 学习天才犹太人的经商法则
- linux删除svn版本库
- 数据库——完整性约束条件
- 永久激活Windows7-最新版本RemoveWAT2.2.6
- 门户网站常用SEO策略及操作规范