动态代理
zhaolengquan Lv3

编译阶段不用关心代理的类,运行阶段才指定代理哪一个对象。

InvocationHandler接口是JDK提供的动态代理接口,

自定义动态代理类实现InvocationHandler接口。

invoke方法是必须实现的,它完成对真实方法的调用,

给定一个接口,动态代理会宣称“已经实现该接口的所有方法了,”动态代理怎么实现被代理接口中的方法呢?

通过InvocationHandler接口,所有方法都通过Handler处理,即所有被代理的方法都由InvocationHandler接管实际的处理任务。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class GamePlayerIH implements InvocationHandler {
Object object = null;

public GamePlayerIH(Object object) {
this.object = object;
}

@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
return method.invoke(object, args);
}
}
public class Client {
public static void main(String[] args) {
iGamePlayer gamePlayer = new GamePlayer("张三");
InvocationHandler handler = new GamePlayerIH(gamePlayer);
iGamePlayer proxyInstance = (iGamePlayer) Proxy.newProxyInstance(gamePlayer.getClass().getClassLoader(),gamePlayer.getClass().getInterfaces(), handler);
proxyInstance.login("zs","123");
proxyInstance.killBoss();
proxyInstance.update();
}
}

第二种方式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class AutoProxy implements InvocationHandler {
private Singer singer;

public Object getproxy(Singer singer) {
this.singer = singer;
Object instance = Proxy.newProxyInstance(singer.getClass().getClassLoader(), singer.getClass().getInterfaces(), this);
return instance;
}

@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("前置通知");
Object invoke = method.invoke(singer);
System.out.println("后置通知");
return invoke;
}
}


Client端
Star star = (Star) new AutoProxy().getproxy(new Singer());
star.show();

第三种方式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public class GamePlayerIH {
Object object = null;
public GamePlayerIH(Object object) {
this.object = object;
}
public Object getproxyInstance() {
return Proxy.newProxyInstance(object.getClass().getClassLoader(),object.getClass().getInterfaces(), new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (method.getName().equalsIgnoreCase("login")) {
System.out.println("快上号看看!!!有人登录你的账号了!!!");
}
return method.invoke(object, args);
}
});
}
}

Client

iGamePlayer gamePlayer = new GamePlayer("zs");
GamePlayerIH gamePlayerIH = new GamePlayerIH(gamePlayer);
iGamePlayer instance = (iGamePlayer)gamePlayerIH.getproxyInstance();
instance.login("zs","123");
instance.killBoss();
instance.update();

参考博客

动态代理

 Comments