阅读jdk动态代理底层源码简单模仿实现的动态代理,最大的收获是明白了如何去阅读源码
public class Test {
public static void main(String[] args) throws Throwable {
/**
* 动态代理:原映雪模仿的动态代理
*/
TestDao proxy = (TestDao) ProxyUtil.newInstance(new TestDaoImpl(), new TestInvocationHandler(new TestDaoImpl()));
proxy.query();
/**
* 动态代理:基于jdk的动态代理
*/
TestDao jdkproxytest1 = (TestDao) Proxy.newProxyInstance(Test.class.getClassLoader(),
new Class[] {
TestDao.class},new TestInvocationHandlerOne(new TestDaoImpl()));
jdkproxytest1.query();
}
}
先写出模板,在按模板和jdk源码的思维来模拟动态代理
public class $Proxy implements TestDao {
private ProxyInvocationHandler target;
public $Proxy (ProxyInvocationHandler target){
this.target =target;
}
@Override
public void query() {
Method method = null;
try {
method = Class.forName("com.yyx.dao.TestDao").getDeclaredMethod("query");
target.invoke(method);
} catch (Exception e) {
e.