1、JDK的动态代理需要依赖接口
2、接口要有实现类,否则动态代理生成的实例意义不大。
动态代理实现方式:
Proxy提供的实现:
static Object | newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h) |
---|
newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h):返回一个实现interfaces接口的动态代理类的实例。
Proxy生成的动态代理类的所有方法实现都将替换成InvocationHandler的invoke(...)方法。
InvocationHandler:
Modifier and Type | Method | Description |
---|---|---|
Object | invoke(Object proxy, Method method, Object[] args) |
当实现InvocationHandler的invoke(...)方法体时,实际上就是为动态代理类的所有方法体提供实现体。
参数说明:
proxy:动态代理生成的实例。
作用:
1. 可以使用反射获取代理对象的信息(也就是proxy.getClass().getName())。
2. 可以将代理对象返回以进行连续调用,这就是proxy存在的主要目的。
method:方法
args:参数
代码:
interface Eatable
{
void taste();
Eatable sayHi(String name);
}
class EatableImpl implements Eatable{
@Override
public void taste() {
System.out.println("--- taste() ---");
}
//返回Eatable,主要是为了能反复调用此方法
@Override
public Eatable sayHi(String name) {
System.out.println("--- sayHi(String name) --- name:"+name);
return null;
}
}
class MyInvocationHandler implements InvocationHandler{
Object object;
public MyInvocationHandler(Object object){
this.object = object;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable{
if(args != null){
method.invoke(object,args);
}else {
method.invoke(object);
}
//返回动态代理对象
return proxy;
}
}
public class ProxyTest1
{
public static void main(String[] args) {
MyInvocationHandler mr = new MyInvocationHandler(new EatableImpl());
Eatable ee = (Eatable)Proxy.newProxyInstance(
Eatable.class.getClassLoader(),
new Class[]{Eatable.class},
mr);
//可以看成调用MyInvocationHandler的invoke(...)方法,返回代理对象一直调用
ee.sayHi("你好").sayHi("我好").sayHi("大家好");
ee.taste();
}
}
结果:
代码解析:
//返回动态代理对象
return proxy;
为什么不用 'this
' 代替?
'this
' 是InvocationHandler他本身, 不是proxy。