Java 第十三章.反射
1.类的加载
类在内存中的生命周期:加载–>使用–>卸载
1.1类的加载过程
类的加载分为三步骤
一 加载:
将class加载到内存中
二 连接:
①验证
校验合法性/正确性(版本对不对)
cafe baby 01010101010101
②准备
准备对应的方法区 创建Class对象 给类变量赋默认值,给静待常量赋初始值
③解析
把字节码中的符号引用替换为对应的直接地址引用(提高效率)
三 类的初始化<clinit>
注意:类的初始化可能会滞后(即使类没有完成初始化,也能够使用部分资源)
1.2类初始化
1.2.1哪些操作会导致类的初始化
(1)运行主方法所在的类,要先完成类初始化,再执行main方法
(2)第一次使用某个类型就是在new它的对象,此时这个类没有初始化的话,先完成类初始化再做实例初始化
(3)调用某个类的静态成员(类变量和类方法),此时这个类没有初始化的话,先完成类初始化
(4)子类初始化时,发现它的父类还没有初始化的话,那么先初始化父类
(5)通过反射操作某个类时,如果这个类没有初始化,也会导致该类先初始化
public class Test1 {
// static {
// System.out.println("类初始化完成!");
// }
public static void main(String[] args) throws ClassNotFoundException {
// new Son();
// System.out.println(Father.id);
Class.forName("包名.Father");
}
}
class Father {
public static int id;
static {
System.out.println("Father类初始化完成!");
}
public static void show() {
System.out.println("Father");
}
}
class Son extends Father {
static {
System.out.println("Son类初始化完成!");
}
}
1.2.2哪些操作不会导致类的初始化
(1)使用某个类的静态的常量(static final)
(2)通过子类调用父类的静态变量,静态方法,只会导致父类初始化,不会导致子类初始化,即只有声明静态成员的类才会初始化
(3)用某个类型声明数组并创建数组对象时,不会导致这个类初始化
public class Test2 {
public static void main(String[] args) {
System.out.println(D.NUM);//D类不会初始化,因为NUM是final的
System.out.println(F.num);
F.test();//F类不会初始化,E类会初始化,因为num和test()是在E类中声明的
//G类不会初始化,此时还没有正式用的G类
G[] arr = new G[5];//没有创建G的对象,创建的是准备用来装G对象的数组对象
//G[]是一种新的类型,是数组类想,动态编译生成的一种新的类型
//G[].class
}
}
class D {
public static final int NUM = 10;
static {
System.out.println("D类的初始化");
}
}
class E {
static int num = 10;
static {
System.out.println("E父类的初始化");
}
public static void test() {
System.out.println("父类的静态方法");
}
}
class F extends E {
static {
System.out.println("F子类的初始化");
}
}
class G {
static {
System.out.println("G类的初始化");
}
}
1.3类加载器(ClassLoader)
1.分类
- 引导类加载器
它负责加载jre/rt.jar核心库
它本身不是Java代码实现的,也不是ClassLoader的子类,获取它的对象时往往返回null - 扩展类加载器
它负责加载jre/lib/ext扩展库
它是ClassLoader的子类 - 应用程序类加载器
它负责加载项目的classpath路径下的类
它是ClassLoader的子类 - 自定义类加载器
当你的程序需要加载“特定”目录下的类,可以自定义类加载器;
当你的程序的字节码文件需要加密时,那么往往会提供一个自定义类加载器对其进行解码
后面会见到的自定义类加载器:tomcat中
2、Java系统类加载器的双亲委托模式
简单描述:
下一级的类加载器,如果接到任务时,会先搜索是否加载过,如果没有,会先把任务往上传,如果都没有加载过,一直到根加载器。
如果根加载器在它负责的路径下没有找到,会往回传,如果一路回传到最后一级都没有找到,那么会报ClassNotFoundException或NoClassDefError,如果在某一级找到了,就直接返回Class对象。
应用程序类加载器 把 扩展类加载器视为父加载器,
扩展类加载器 把 引导类加载器视为父加载器。
不是继承关系,是组合的方式实现的。
3.理解
package 反射;
import org.junit.Test;
public class ClassLoaderTest1 {
@Test
public void test1(){
//对于自定义类,使用应用程序类加载器进行加载
ClassLoader classLoader1 = ClassLoaderTest1.class.getClassLoader();
System.out.println(classLoader1);
//调用系统类加载器的getParent():获取扩展类加载器
ClassLoader classLoader2 = classLoader1.getParent();
System.out.println(classLoader2);
//调用扩展类加载器的getParent():无法获取引导类加载器
//引导类加载器主要负责加载java的核心类库,无法加载自定义类的
ClassLoader classLoader3 = classLoader2.getParent();
System.out.println(classLoader3);
ClassLoader classLoader4 = String.class.getClassLoader();
System.out.println(classLoader4);
}
}
4.使用ClassLoader加载配置文件
@Test
public void test2() throws IOException {
Properties pros = new Properties();
//读取配置文件方式一:
//此时的文件默认在当前模板下
//FileInputStream fis = new FileInputStream("jdbc.properties");
//FileInputStream fis = new FileInputStream("src\\jdbc.properties");
//pros.load(fis);
//读取配置文件方式二:
//此时的文件默认在src下
ClassLoader classLoader = ClassLoaderTest1.class.getClassLoader();
InputStream is = classLoader.getResourceAsStream("jdbc.properties");
pros.load(is);
String user = pros.getProperty("username");
String password = pros.getProperty("password");
System.out.println("username:" + user + ",password:" + password);
}
2.概述
3.理解Class类并获取Class实例
3.1关于Java.lang.Class类的理解
1.类的加载过程
程序经过javac.exe命令以后,会生成一个或多个字节码文件(.class结尾)。
接着我们使用java.exe命令对某个字节码文件进行解释运行,相当于将某个字节码文件加载到内存中。
此过程就称为类的加载。
加载到内存中的类,我们就称为运行时类,此运行时类,就作为Class的一个实例
2.
换句话说,Class的实例就对应着一个运行实例
3.
加载到内存中的运行时类,会缓存一定的时间。
在此时间之内,我们可以通过不同的方式来获取此运行时的类
3.2获取Class实例的四种方式
package 反射;
import org.junit.Test;
import sun.misc.Ref;
public class ReflectionPerson {
//反射之前,对于Person类的操作
@Test
public void test1() {
//1.创建对象
Person person1 = new Person("Tom", 19);
//2.调用属性和方法
person1.setAge(22);
System.out.println(person1.toString());
person1.show();
}
//获取Class实例
@Test
public void test2() throws Exception {
//方式一:调用运行时类的属性
Class<Person> clazz1 = Person.class;
System.out.println(clazz1);
//2.通过运行时类的对象,调用getClass()
Person p1 = new Person();
Class<? extends Person> clazz2 = p1.getClass();
System.out.println(clazz2);
//3.调用Class的静态方法:forName(String classPath)
Class<?> clazz3 = Class.forName("反射.Person");
System.out.println(clazz3);
System.out.println(clazz1 == clazz2);
System.out.println(clazz1 == clazz2);
//4.使用类的加载器:ClassLoader
ClassLoader classLoader = ReflectionPerson.class.getClassLoader();
Class clazz4 = classLoader.loadClass("反射.Person");
System.out.println(clazz4);
System.out.println(clazz1 == clazz4);
}
}
3.3Class实例对应的结构说明
(1)class: 外部类,成员(成员内部类,静态内部类),局部内部类,匿名内部类
(2)interface:接口
(3)[]:数组
(4)enum:枚举
(5)annotation:注解@interface
(6)primitive type:基本数据类型
(7)void
@Test
public void test3(){
Class c1 = Object.class;
Class c2 = Comparable.class;
Class c3 = String[].class;
Class c4 = int[][].class;
Class c5 = ElementType.class;
Class c6 = Override.class;
Class c7 = int.class;
Class c8 = void.class;
Class c9 = Class.class;
int[] a = new int[10];
int[] b = new int[100];
Class c10 = a.getClass();
Class c11 = b.getClass();
// 只要元素类型与维度一样,就是同一个Class
System.out.println(c10 == c11);
}
4.创建运行时类的对象
@Test
public void test1() throws InstantiationException, IllegalAccessException {
Class<Person> clazz = Person.class;
/*
newInstance():调用此方法,创建对应的运行时类的对象。
内部调用了运行时类的空参构造器。
要想此方法正常的创建运行时类的对象,要求:
1.运行时类必须通过空参构造器
2.空参构造器的访问权限得够,一般设为public
在javabean中要求提供一个public的空参构造器
原因:
1.便于通过反射,创建运行时类的对象
2.便于子类继承此运行时类时,默认调用super()时,保证父类有此构造器
*/
Person person = clazz.newInstance();
System.out.println(person);
}
5.获取运行时类的完整结构(了解)
6.调用运行时类的指定结构
6.1调用运行时类中的指定属性
@Test//不需要掌握
public void test1() throws Exception {
Class<Person> clazz = Person.class;
//创建运行时类的对象
Person p = clazz.newInstance();
//获取指定属性:要求属性权限public(因此不常用)
Field id = clazz.getField("id");
//设置当前属性的值
//set():参数一指明设置那个对象的属性,参数二设置属性值
id.set(p,1001);
//获取属性值
//参数一指明设置那个对象的属性,
Object o = id.get(p);
int idp = (int)o;
System.out.println(idp);
}
@Test
public void test2() throws Exception {
Class<Person> clazz = Person.class;
//创建运行时类的对象
Person p = clazz.newInstance();
//1.获取运行时类的指定变量名的属性
Field name = clazz.getDeclaredField("name");
//2.保证当前属性是可以访问的
name.setAccessible(true);
//3.设置属性值
name.set(p,"Tom");
//4.获取属性值
Object o = name.get(p);
String namep =(String)o;
System.out.println(namep);
}
6.2调用运行时类的指定方法
@Test
public void test3() throws Exception {
Class<Person> clazz = Person.class;
//创建运行时类的对象
Person p = clazz.newInstance();
//1.获取指定的某个方法
//getDeclaredMethod("show", String.class);参数一:指明获取的方法的名称 参数二:指明获取方法的形参列表
Method show = clazz.getDeclaredMethod("showNation", String.class);
//2.保证当前方法是可以访问的
show.setAccessible(true);
//3.调用方法的invoke():参数一:方法的调用者 参数二:给方法形参复制的实参
//invoke()返回值即为对应类中调用的方法的返回值
Object chian = show.invoke(p, "chian");
System.out.println(chian);
System.out.println("*************如何调用静态方法***********");
Method showDesc = clazz.getDeclaredMethod("showDesc");
showDesc.setAccessible(true);
//如果调用的运行时类的方法,没有返回值,则返回null
Object invoke = showDesc.invoke(Person.class);
System.out.println(invoke);
}
6.3调用运行时类中的指定构造器
@Test
public void test4() throws Exception {
Class<Person> clazz = Person.class;
// private Person(String name)
//1.获取指定构造器
//getDeclaredConstructor():参数:指明构造器的形参列表
Constructor<Person> constructor = clazz.getDeclaredConstructor(String.class);
//2.保证此构造器是可以访问的
constructor.setAccessible(true);
//3.调用此构造器创建运行时类的对象
Person tom = constructor.newInstance("Tom");
System.out.println(tom);
}
7.反射的应用:动态代理
7.1概述
代理设计模式的原理:
使用一个代理将对象包装起来, 然后用该代理对象取代原始对象。
任何对原始对象的调用都要通过代理。
代理对象决定是否以及何时将方法调用转到原始对象上。
之前为大家讲解过代理机制的操作,属于静态代理,特征是代理类和目标对象的类都是在编译期间确定下来,不利于程序的扩展。
同时,每一个代理类只能为一个接口服务,这样一来程序开发中必然产生过多的代理。最好可以通过一个代理类完成全部的代理功能。
动态代理是指客户通过代理类来调用其它对象的方法,并且是在程序运行时
根据需要动态创建目标类的代理对象。
动态代理使用场合:
调试
远程方法调用
动态代理相比于静态代理的优点:
抽象角色中(接口)声明的所有方法都被转移到调用处理器一个集中的方法中处理,这样,我们可以更加灵活和统一的处理众多的方法。
7.2静态代理和动态代理
静态代理
package 反射.动态代理;
import sun.applet.Main;
import java.net.Proxy;
//静态代理
//特点:代理类和被代理类在编译期间,就确定下来了。
public class StaticProxyTest {
public static void main(String[] args) {
//被代理类对象
NikeClothFactory nikeClothFactory = new NikeClothFactory();
//代理类对象
ProxyClothFactory proxyClothFactory = new ProxyClothFactory(nikeClothFactory);
proxyClothFactory.produceCloth();
}
}
interface ClothFactory{
void produceCloth();
}
//代理类
class ProxyClothFactory implements ClothFactory{
private ClothFactory factory;//有被代理类对象实例化
public ProxyClothFactory(ClothFactory factory){
this.factory=factory;
}
@Override
public void produceCloth() {
System.out.println("代理类之前");
factory.produceCloth();
System.out.println("代理类之后");
}
}
//被代理类
class NikeClothFactory implements ClothFactory{
@Override
public void produceCloth() {
System.out.println("被代理类");
}
}
动态代理
package 反射.动态代理;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
//动态代理
//问题一:如何根据加载到内存中的被代理类,动态的创建一个代理类及其对象
//问题二:当通过代理类的对象调用方法时,如何动态地去调用被代理类中的同名
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("烧烤");
}
}
interface Human{
String getBelief();
void eat(String food);
}
//被代理类
class Superman implements Human{
@Override
public String getBelief() {
return "iu";
}
@Override
public void eat(String food) {
System.out.println("我喜欢吃:" + food);
}
}
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()中
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//method:即为代理类对象调用的方法,此方法也就作为了被代理类对象要调用的方法
//obj:被代理类的对象
Object returnValue = method.invoke(obj,args);
//上述方法的返回值就作为当前类中的invoke()的返回值
return returnValue;
}
}