一、动态代理
|--Proxy
static Object newProxyInstance(
ClassLoader loader, 目标对象使用的类加载器
Class<?>[] interfaces, 目标对象实现的接口类型
InvocationHandler h 事件处理器:当执行上面接口中
的方法的时候,就会自动触发事
件处理器代码,把当前执行的方法(method)作为参数传入。
)
接口:
public interface HelloInterface {
void sayHello();
}
被代理类:
public class Hello implements HelloInterface{
@Override
public void sayHello() {
System.out.println(" hello ");
}
}
代理类:
//代理类
public class HelloProxy implements InvocationHandler{
private Object obj;
public HelloProxy(Object obj) {
this.obj=obj;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object result=null;
//获取方法名
String methodName = method.getName();
if("sayHello".equals(methodName)) {
System.out.println("代理类新增逻辑..");
result= method.invoke(obj, args);
}else {
result = method.invoke(obj, args);
}
return result;
}
}
使用:
public class Demo {
public static void main(String[] args) {
HelloInterface hello=new Hello();
/**方式一:使用动态代理类创建代理对象*/
//创建动态代理对象
HelloInterface proxy=(HelloInterface) Proxy.newProxyInstance(HelloInterface.class.getClassLoader(), hello.getClass().getInterfaces(), new HelloProxy(hello));
proxy.sayHello();
/**方式二:使用匿名对象创建代理对象*/
//创建动态代理对象
HelloInterface proxy2=(HelloInterface) Proxy.newProxyInstance(HelloInterface.class.getClassLoader(), hello.getClass().getInterfaces(), new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//获取方法名
System.out.println("代理类新增逻辑..");
return method.invoke(hello, args);
}
});
proxy.sayHello();
}
}