动态代理用Proxy类里的newProxyInstance方法,在java.lang.reflect包里
public static Object newProxyInstance(ClassLoader loader,
Class<?>[] interfaces,
InvocationHandler h)
参数如下
* @param loader the class loader to define the proxy class
* @param interfaces the list of interfaces for the proxy class
* to implement
* @param h the invocation handler to dispatch method invocations to
* @return a proxy instance with the specified invocation handler of a
* proxy class that is defined by the specified class loader
* and that implements the specified interfaces
具体说明:
ClassLoader loader,
:指定当前目标对象使用类加载器,获取加载器的方法是固定的Class<?>[] interfaces,
:目标对象实现的接口的类型,使用泛型方式确认类型InvocationHandler h
:事件处理,执行目标对象的方法时,会触发事件处理器的方法,会把当前执行目标对象的方法作为参数传入
参考:https://www.cnblogs.com/cenyu/p/6289209.html
动态代理不需要代理类实现接口
首先是接口类
package com.lihuia.proxy;
/**
* Copyright (C), lihuia.com
* FileName: IUserDao
* Author: lihui
* Date: 2019/1/1
*/
public interface IUserDao {
void save();
}
然后目标类,实现了接口
package com.lihuia.proxy;
/**
* Copyright (C), lihuia.com
* FileName: UserDao
* Author: lihui
* Date: 2019/1/1
*/
public class UserDao implements IUserDao {
@Override
public void save() {
System.out.println("----已经保存数据!----");
}
}
接着是代理类,这是代理工厂类
package com.lihuia.proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
/**
* Copyright (C), lihuia.com
* FileName: ProxyFactory
* Author: lihui
* Date: 2019/1/5
*/
public class ProxyFactory {
private Object target;// 维护一个目标对象
public ProxyFactory(Object target) {
this.target = target;
}
// 为目标对象生成代理对象
public Object getProxyInstance() {
return Proxy.newProxyInstance(
target.getClass().getClassLoader(),
target.getClass().getInterfaces(),
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("开启事务");
// 执行目标对象方法
Object returnValue = method.invoke(target, args);
System.out.println("提交事务");
return null;
}
}
);
}
}
测试类
package com.lihuia.proxy;
import org.testng.annotations.Test;
/**
* Copyright (C), lihuia.com
* FileName: ProxyTest
* Author: lihui
* Date: 2019/1/5
*/
public class ProxyTest {
@Test
public void testDynamicProxy() {
IUserDao target = new UserDao();
System.out.println(target.getClass());
IUserDao proxy = (IUserDao) new ProxyFactory(target).getProxyInstance();
System.out.println(proxy.getClass());
proxy.save();
}
}
挺难理解的