创建需要被代理的接口并实现
package com.example.javase;
/**
* @Description: Proxy 代理必须要接口 (被代理的类)
* @author: YZD
* @Date: 2020-02-10 20:45
* @Version: 1.0
*/
public interface ProxyInterface {
public void show();
}
class ProxyInterfaceIml implements ProxyInterface {
@Override
public void show() {
System.out.println(this.getClass().getName());
}
}
创建代理类 并通过main方法测试
package com.example.javase;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
/**
* @Description: Java动态代理类
* @author: YZD
* @Date: 2020-02-10 17:09
* @Version: 1.0
*/
public class day09 implements InvocationHandler {
/**
* 动态代理:Proxy
* 专门完成代理的操作类,是所有动态代理的父类,
* 通过此类为一或多个接口实现动态生成实现类
*/
// 代理的对象
Object object;
public day09(Object object) {
this.object = object;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("方法执行前。。");
Object obj = method.invoke(this.object, null);
System.out.println("方法执行后。。");
return obj;
}
public static void main(String[] args) {
ProxyInterface proxyInterface = new ProxyInterfaceIml();
InvocationHandler invocationHandler = new day09(proxyInterface);
//参数:代理的类加载器 代理对象的接口 代理的对象
//返回值:代理成功后的对象
//通过返回的对象 在执行操作
// Proxy.newProxyInstance 这种代理必须要 接口
ProxyInterface p = (ProxyInterface) Proxy.newProxyInstance(invocationHandler.getClass().getClassLoader(), proxyInterface.getClass().getInterfaces(), invocationHandler);
p.show();
}
}
结果