java动态代理
目标接口
public interface Target {
void cat();
}
实现目标接口
public class TargetImpl implements Target {
@Override
public void cat() {
System.out.println("这是一只Limao");
}
}
对目标接口的实现做增强
public class ProxyInvocationHandler implements InvocationHandler {
private Object target;
public ProxyInvocationHandler(Object target) {
this.target = target;
}
//对方法做增强
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("增强前.......");
//原来的业务处理逻辑
Object invoke = method.invoke(target, args);
System.out.println("增强后.......");
return invoke;
}
}
客户端
public class Client {
public static void main(String[] args) {
//是否生成代理类Class文件开关
String name = "sun.misc.ProxyGenerator.saveGeneratedFiles";
System.setProperty(name, "true");
String result = System.getProperty(name);
System.out.println(result);
Target targetClass = new TargetImpl();
ProxyInvocationHandler proxyInvocationHandler = new ProxyInvocationHandler(targetClass);
Target target = (Target)Proxy.newProxyInstance(Client.class.getClassLoader(),
new Class<?>[]{Target.class},
proxyInvocationHandler
);
target.cat();
}
}
saveGeneratedFiles是控制是否生成代理类文件的开关
生成的代理类
public final class $Proxy0 extends Proxy implements Target {
//原接口中的方法
private static Method m1;
private static Method m2;
private static Method m3;
private static Method m0;
public $Proxy0(InvocationHandler var1) throws {
super(var1);
}
public final boolean equals(Object var1) throws {
try {
return (Boolean)super.h.invoke(this, m1, new Object[]{var1});
} catch (RuntimeException | Error var3) {
throw var3;
} catch (Throwable var4) {
throw new UndeclaredThrowableException(var4);
}
}
public final String toString() throws {
try {
return (String)super.h.invoke(this, m2, (Object[])null);
} catch (RuntimeException | Error var2) {
throw var2;
} catch (Throwable var3) {
throw new UndeclaredThrowableException(var3);
}
}
public final void cat() throws {
try {
super.h.invoke(this, m3, (Object[])null);
} catch (RuntimeException | Error var2) {
throw var2;
} catch (Throwable var3) {
throw new UndeclaredThrowableException(var3);
}
}
public final int hashCode() throws {
try {
return (Integer)super.h.invoke(this, m0, (Object[])null);
} catch (RuntimeException | Error var2) {
throw var2;
} catch (Throwable var3) {
throw new UndeclaredThrowableException(var3);
}
}
static {
try {
m1 = Class.forName("java.lang.Object").getMethod("equals", Class.forName("java.lang.Object"));
m2 = Class.forName("java.lang.Object").getMethod("toString");
m3 = Class.forName("org.example.Target").getMethod("cat");
m0 = Class.forName("java.lang.Object").getMethod("hashCode");
} catch (NoSuchMethodException var2) {
throw new NoSuchMethodError(var2.getMessage());
} catch (ClassNotFoundException var3) {
throw new NoClassDefFoundError(var3.getMessage());
}
}
}