/**
* @author huzhongkang
* @Title: ${file_name}
* @date 2020/5/269:52
*/
public interface PersonDao {
void save();
void delete();
}
/**
* @author huzhongkang
* @Title: ${file_name}
* @date 2020/5/269:54
*/
public class PersonDaoImpl implements PersonDao{
public void save() {
System.out.println("成功保存数据。。。。");
}
public void delete() {
System.out.println("成功删除数据。。。。");
}
}
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
/**
* @author huzhongkang
* @Title: ${file_name}
* @date 2020/5/2611:06
*/
public class ProxyPerosn {
//获取当前类的代理对象 jdk提供代理类proxy的newProxyInstance方法获取需要代理对象的代理类
public static PersonDao getProxy(final PersonDaoImpl personDao) {
//需要代理对象的类加载器
ClassLoader classLoader = personDao.getClass().getClassLoader();
//an array of interfaces implemented by this class.
Class<?>[] interfaces = personDao.getClass().getInterfaces();
//采用匿名内部类的方式处理InvocationHandler接口
//根据reflect的Proxy生成代理对象
Object o = Proxy.newProxyInstance(classLoader, interfaces, new InvocationHandler() {
//method:代表目标对象的方法。。
//proxy代表需要被代理的目标对象
//args 方法参数列表
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//利用jdk反射执行方法 并且返回方法执行结果
System.out.println(method.getName() + " 方法执行........");
Object invoke = method.invoke(personDao, args);
System.out.println("方法执行结果:" + invoke);
return invoke;
}
});
//返回代理对象
return (PersonDao)o;
}
public static void main(String[] args) {
PersonDaoImpl personDao = new PersonDaoImpl();
PersonDao proxy = ProxyPerosn.getProxy(personDao);
proxy.save();
proxy.delete();
}
}
save 方法执行........
成功保存数据。。。。
方法执行结果:null
delete 方法执行........
成功删除数据。。。。
方法执行结果:null