歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Java動態代理簡單實現

Java動態代理簡單實現

日期:2017/3/1 10:30:49   编辑:Linux編程

Java動態代理簡單實現:

  1. package com.dynamic.proxy;
  2. public class ProxyDemo {
  3. public static void main(String[] args) throws SecurityException, NoSuchMethodException {
  4. LogHandler logHandler = new LogHandler();
  5. IHello hello = (IHello)logHandler.bind(new HelloImp());
  6. hello.toHello("cross");
  7. hello.toHello1("cross");
  8. }
  9. }

  1. package com.dynamic.proxy;
  2. import java.lang.reflect.InvocationHandler;
  3. import java.lang.reflect.Method;
  4. import java.lang.reflect.Proxy;
  5. public class LogHandler implements InvocationHandler {
  6. private Object deledate;
  7. public Object bind(Object deledate){
  8. this.deledate = deledate;
  9. Object proxy = Proxy.newProxyInstance(deledate.getClass().getClassLoader(), deledate.getClass().getInterfaces(), this);
  10. return proxy;
  11. }
  12. public Object invoke(Object proxy, Method method, Object[] obj)
  13. throws Throwable {
  14. doBefore();
  15. Object result = method.invoke(deledate, obj);
  16. doAfter();
  17. return result;
  18. }
  19. private void doBefore() {
  20. System.out.println("before....");
  21. }
  22. private void doAfter() {
  23. System.out.println("after....");
  24. }
  25. }

  1. package com.dynamic.proxy;
  2. public interface IHello {
  3. public void toHello(String name);
  4. public void toHello1(String name);
  5. }

  1. package com.dynamic.proxy;
  2. public class HelloImp implements IHello {
  3. public void toHello(String name) {
  4. System.out.println("method hello:" + name);
  5. }
  6. public void toHello1(String name) {
  7. System.out.println("method hello1:" + name);
  8. }
  9. }
Copyright © Linux教程網 All Rights Reserved