1.package com;
2.
3.public interface IComponent {
4.public void business1() ;
5.public void business2() ;
6.public void business3() ;
7.}
package com;
1.public class Component implements IComponent{
2. public void business1() {
3. System.out.println("业务1");
4. }
5.
6. public void business2() {
7. System.out.println("业务2");
8. }
9.
10. public void business3() {
11. System.out.println("业务3");
12. }
13.}
package com
1.import java.lang.reflect.InvocationHandler;
2.import java.lang.reflect.Method;
3.import java.lang.reflect.Proxy;
4.
5.public class DynamicProxy implements InvocationHandler {
6. private Object obj;
7. //private DynamicProxy p;
8.
9. public Object bindl(Object obj) {
10. this.obj = obj;
11. System.out.println("我是bind*****");
12. return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj
13. .getClass().getInterfaces(),this);// 用来动态装载invoke方法的
14. // return new DynamicProxy() ;
15. //创建代理类 实例化了一个代理类
16. }
17.
18. // 动态调用的 不需要手的设置装载
19. public Object invoke(Object proxy, Method method, Object[] args)
20. throws Throwable {
21. // TODO Auto-generated method stub
22. // System.out.println(proxy.getClass());
23. // System.out.println(method.getClass());
24. Object result = null;
25. try {
26. valiateUser();
27. // System.out.println(proxy.getClass());
28. // System.out.println(args);
29. // System.out.println(method.getClass());
30. result = method.invoke(obj,args);// 调用方法 obj
31. // System.out.println(result);
32. System.out.println("************");
33. } catch (Exception e) {
34. e.printStackTrace();
35. }
36. return result;
37. }
38.
39. public void valiateUser() {
40. System.out.println("验证用户。。。。");
41. }
42.}
package com;
1.public class TestD {
2.public static void main(String args[]){
3. DynamicProxy proxy = new DynamicProxy();
4. IComponent component=(IComponent) proxy.bindl(new Component());
5. component.business1();//先调用它的invoke方法 再在他的invoke方法里面加载类
6. component.business2();
7. component.business3();
8.
9.
10.}
11.}