Java—— 动态代理
代理的作用
对象如果嫌身上干的事太多的话,可以通过代理来转移部分职责。也就是说,代理可以无侵入式的给对象增强其他的功能
使用代理时,调用者先调用代理中的方法,让代理做一些准备工作,再由代理调用对象中的方法,从而增强了对象的功能
代理中的方法
对象有什么方法想被代理,代理就一定要有对应的方法。代理里面的方法就是对象要被代理的方法
使用接口将代理与对象中的方法统一起来
创建代理对象
java.lang.reflect.Proxy类:提供了为对象产生代理对象的方法
public static object newProxyInstance(参数一,参数二,参数三) 参数一:ClassLoader loader 用于指定用哪个类加载器,去加载生成的代理类
参数二:Class<?>[] interfaces 指定接口,用于指定生成的代理,也就是有哪些方法
参数三:InvocationHandler h 用来指定生成的代理对象要干什么事情
代码演示
接口
public interface PersonInterface {//把所有要代理的方法定义在接口中public abstract String eat(String food);public abstract void sleep();
}
Person类
public class Person implements PersonInterface {private String name;public Person() {}public Person(String name) {this.name = name;}public String getName() {return name;}public void setName(String name) {this.name = name;}@Overridepublic String eat(String food) {System.out.println(name + "吃了" + food);return "吃完了";}@Overridepublic void sleep() {System.out.println(name + "正在睡觉");}public String toString() {return "Person{name = " + name + "}";}
}
创建代理工具类
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;//工具类创建代理
public class ProxyUtil {public static PersonInterface creatProxy(Person person){//参数一:用于指定用哪个类加载器,去加载生成的代理类//参数二:指定接口,用于指定生成的代理,也就是有哪些方法//参数三:用来指定生成的代理对象要干什么事情//返回值:创建的代理PersonInterface pi = (PersonInterface) Proxy.newProxyInstance(ProxyUtil.class.getClassLoader(),new Class[]{PersonInterface.class},new InvocationHandler() {@Overridepublic Object invoke(Object proxy, Method method, Object[] args) throws Throwable {//参数一:代理的对象//参数二:要运行的方法//参数三:调用方法时,传递的实参if ("eat".equals(method.getName())){System.out.println("准备碗筷");} else if ("sleep".equals(method.getName())) {System.out.println("准备床铺");}//反射return method.invoke(person,args);}});return pi;}
}
测试类
public class Test {public static void main(String[] args) {//获取代理Person p = new Person("张三");PersonInterface pi = ProxyUtil.creatProxy(p);//调用eat方法String result = pi.eat("米饭");System.out.println(result);//准备碗筷//张三吃了米饭//吃完了//调用sleep方法pi.sleep();//准备床铺//张三正在睡觉}
}