java实现代理可以通过java.lang.reflect.Proxy接口结合java.lang.reflect.InvocationHandler来实现
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class ProxyHandler implements InvocationHandler {
private UserService object;
public ProxyHandler() {
this.object = new UserServiceImpl();
}
public UserService newProxyInstance(){
return (UserService) Proxy.newProxyInstance(this.object.getClass().getClassLoader(), this.object.getClass().getInterfaces(), this);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("预处理");
Object object = method.invoke(this.object, args);
if(object instanceof Person) {
((Person) object).setName("姓名:" + ((Person) object).getName());
}
System.out.println("后处理");
return object;
}
}
通过如下方法调用生成代理的对象
public class Test {
public static void main(String[] args) {
ProxyHandler proxyHandler = new ProxyHandler(); //生成代理类初始化被代理类
UserService userService = proxyHandler.newProxyInstance(); //生成代理实例
System.out.println(userService.getUserInfo(1).getName()); //调用被代理方法
}
}
此时代理类内自定义的invoke方法将会在被代理方法执行前后执行自定义的操作
控制台输出结果
预处理
后处理
姓名:libiyi
如下是源码
public static Object newProxyInstance(ClassLoader loader,
Class>[] interfaces,
InvocationHandler h)
throws IllegalArgumentException
{
Objects.requireNonNull(h);
final Class>[] intfs = interfaces.clone();
final SecurityManager sm = System.getSecurityManager();
if (sm != null) {
checkProxyAccess(Reflection.getCallerClass(), loader, intfs);
}
/*
* 从缓存中获取到代理类
*/
Class> cl = getProxyClass0(loader, intfs);
try {
if (sm != null) {
checkNewProxyPermission(Reflection.getCallerClass(), cl);
}
final Constructor> cons = cl.getConstructor(constructorParams);//获取到代理类的构造器
final InvocationHandler ih = h;
if (!Modifier.isPublic(cl.getModifiers())) {
AccessController.doPrivileged(new PrivilegedAction() {
public Void run() {
cons.setAccessible(true);
return null;
}
});
}
return cons.newInstance(new Object[]{h});//生成代理类实例
} catch (IllegalAccessException|InstantiationException e) {
throw new InternalError(e.toString(), e);
} catch (InvocationTargetException e) {
Throwable t = e.getCause();
if (t instanceof RuntimeException) {
throw (RuntimeException) t;
} else {
throw new InternalError(t.toString(), t);
}
} catch (NoSuchMethodException e) {
throw new InternalError(e.toString(), e);
}
}
从如上代码可见,首先需要获取代理类,然后再获取到代理类构造器,最后使用构造器生成代理类实例。
关键的代理类获取在getProxyClass0方法、和getConstructor中
private static Class> getProxyClass0(ClassLoader loader,
Class>... interfaces) {
if (interfaces.length > 65535) {
throw new IllegalArgumentException("interface limit exceeded");
}
// If the proxy class defined by the given loader implementing
// the given interfaces exists, this will simply return the cached copy;
// otherwise, it will create the proxy class via the ProxyClassFactory
return proxyClassCache.get(loader, interfaces);
}
private static final WeakCache[], Class>>
proxyClassCache = new WeakCache<>(new KeyFactory(), new ProxyClassFactory());
在getProxyClass0方法中,使用了关键的WeakCache类,其中的结构是ConcurrentMap