動態代理理解
-
- public interface XiangQinInterface {
-
- public void xiangQin();
- }
-
- public class ZhangSanXiangQinInterfaceImpl implements XiangQinInterface {
- public void xiangQin() {
- System.out.println("張三去相親,娶個漂亮老婆。");
- }
- }
- import java.lang.reflect.InvocationHandler;
- import java.lang.reflect.Method;
-
-
- public class ReadyInvocationHandler implements InvocationHandler {
- //相親接口的實現類,也就是張三相親類
- private Object zhangSan = null;
-
- public ReadyInvocationHandler(Object realSubject) {
- this.zhangSan = realSubject;
- }
-
- public Object invoke(Object proxy, Method m, Object[] args) {
- Object result = null;
- try {
-
-
- System.out.println(proxy.getClass().getSimpleName());
- System.out.println("張三相親前,代理人給他打扮了打扮。");
- result = m.invoke(zhangSan, args);
- } catch (Exception ex) {
- System.exit(1);
- }
- return result;
- }
- }
- import java.lang.reflect.InvocationHandler;
- import java.lang.reflect.Method;
- import java.lang.reflect.Proxy;
-
-
- public class HunJieSuo {
- public static void main(String args[]) {
- //先將張三相親這個相親的實現類實例化,也就是獲得XiangQinInterface接口的一個實例對象
- XiangQinInterface zhangSan = new ZhangSanXiangQinInterfaceImpl();
-
-
- XiangQinInterface proxy = (XiangQinInterface) Proxy.newProxyInstance(
- zhangSan.getClass().getClassLoader(),
- zhangSan.getClass().getInterfaces(),
- new ReadyInvocationHandler(zhangSan));
- proxy.xiangQin();
-
- }
- }
歡迎關注本站公眾號,獲取更多信息