JDK动态代理
接口
package p2;
public interface IService {
public void add();
public int delete(int i);
}
实现类
package p2;
public class ServiceImpl implements IService{
@Override
public void add() {
System.out.println("增加了一条信息");
}
@Override
public int delete(int i) {
System.out.println("删除了"+i+"条数据");
return i;
}
}
代理类生成类
package p2;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;
public class DynamicProxyCreate<T>{
private Object target;
public DynamicProxyCreate(Object target) {
this.target = target;
}
@SuppressWarnings("unchecked")
public T getProxyInstance() {
Class<? extends Object> c = target.getClass();
return (T) Proxy.newProxyInstance(c.getClassLoader(), c.getInterfaces(), new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
preInvoke(method, args);
Object res = method.invoke(target, args);
afterInvoke(res);
return res;
}
});
}
private void preInvoke(Method method,Object[] args) {
String className = target.getClass().getName();
String methodName = method.getName();
if (args==null||args.length==0) {
System.out.println("执行了"+className+"\t"+methodName+"()");
}else {
System.out.println("执行了"+className+"\t"+methodName+"()\t方法参数"+Arrays.asList(args));
}
}
private void afterInvoke(Object res) throws Exception{
if (res==null) {
System.out.println("方法无返回值");
}else {
System.out.println("方法返回值为\t"+res);
}
}
}
测试
package p2;
public class Main {
public static void main(String[] args) {
DynamicProxyCreate<IService> instance = new DynamicProxyCreate<>(new ServiceImpl());
IService service = instance.getProxyInstance();
service.add();
service.delete(1);
}
}
测试结果
执行了p2.ServiceImpl add()
增加了一条信息
方法无返回值
执行了p2.ServiceImpl delete() 方法参数[1]
删除了1条数据
方法返回值为 1