使用Proxy的newProxyInstance方法创建动态代理。
public static Object newProxyInstance(ClassLoader loader,
Class<?>[] interfaces,
InvocationHandler h)
loader:自然是类加载器
interfaces:需要代理的接口
h:InvocationHandler对象
public interface InvocationHandler{
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable;
}
proxy :代理对象
method:代理对象调用的方法
args:调用的方法中的参数
例子
package com.cimon.simplerpc.prework;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
/**
* @author chenrenbing
* @date 2021/06/20
* 动态代理模式
* */
public class DynamicProxyDemo {
public static void main(String args[]){
WineService wineService1 = new WineServiceImpl1();
WineService wineService2 = new WineServiceImpl2();
InvocationHandler handler1 = new WineHandler(wineService1);
InvocationHandler handler2 = new WineHandler(wineService2);
WineService proxy1 = (WineService) Proxy.newProxyInstance(WineService.class.getClassLoader(),wineService1.getClass().getInterfaces(),handler1);
proxy1.sellWine();
proxy1.amount(1499);
WineService proxy2 = (WineService) Proxy.newProxyInstance(WineService.class.getClassLoader(),wineService1.getClass().getInterfaces(),handler2);
proxy2.sellWine();
proxy2.amount(999);
}
}
interface WineService{
void sellWine();
int amount(int a);
}
class WineServiceImpl1 implements WineService{
public void sellWine(){
System.out.println(" 茅台... ");
}
public int amount(int a){
System.out.println(" 茅台价格 : "+ a+"元");
return a;
}
}
class WineServiceImpl2 implements WineService{
public void sellWine(){
System.out.println(" 五粮液... ");
}
public int amount(int a){
System.out.println(" 五粮液 : "+ a+"元");
return a;
}
}
class WineHandler implements InvocationHandler{
private Object wine;
public WineHandler(Object wine){
this.wine = wine;
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable{
System.out.println(" 卖酒了..." + this.wine.getClass().getSimpleName());
Object result = method.invoke(wine,args);
System.out.println(" 卖完了....");
return result;
}
}
运行结果:
卖酒了...WineServiceImpl1
茅台...
卖完了....
卖酒了...WineServiceImpl1
茅台价格 : 1499元
卖完了....
卖酒了...WineServiceImpl2
五粮液...
卖完了....
卖酒了...WineServiceImpl2
五粮液 : 999元
卖完了....
参考
1、java中的代理模式