方法一: 自己實現invocationHandler
package com.czh.Utils;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class proxy_class<T> implements InvocationHandler {
private Class<T> target_class;
public proxy_class(Class<T> target_class) {
this.target_class = target_class;
}
public Object newInstance () {
return Proxy.newProxyInstance(target_class.getClassLoader(),target_class.getInterfaces(),this);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("這是動態代理實現類!");
method.invoke(target_class.newInstance(),args);
return null;
}
}
方法二 :
package com.czh.Utils;
import com.czh.domain.impl.userDaoimpl;
import com.czh.domain.userDao;
import com.sun.deploy.net.proxy.ProxyHandler;
import org.junit.Test;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class jdkpoxy {
public static void main(String[] args) {
userDao UD = new userDaoimpl();
/* userDao proxy =(userDao) new Proxy.getInvocationHandler();*/
/*匿名內部類 實現*/
userDao proxy = (userDao)Proxy.newProxyInstance(jdkpoxy.class.getClassLoader(),
UD.getClass().getInterfaces(),
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("系統執行前:"+System.currentTimeMillis());
return method.invoke(UD, args);
}
});
proxy.eat("小明!");
proxy.run();
}
/*測試 方法一 實現類*/
@Test
public void demo2(){
proxy_class<userDaoimpl> userDaoimplproxy_class = new proxy_class<>(userDaoimpl.class);
userDao o = (userDao)userDaoimplproxy_class.newInstance();
o.eat("王雪雪");
o.run();
}
}