Guest User

Untitled

a guest
Feb 18th, 2018
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.60 KB | None | 0 0
  1. //this example from last year’s text…remove package and modify as per hw directions
  2.  
  3. //package app.proxy.dynamic;
  4.  
  5. import java.lang.reflect.InvocationHandler;
  6. import java.lang.reflect.Method;
  7. import java.lang.reflect.Proxy;
  8.  
  9. /**
  10. This class is an example of a dynamic proxy. Instances of this class wrap a
  11. proxied object. This class simply forwards calls to the object it wraps.
  12. However, if any method takes a long time to execute, this class will print a
  13. warning message.
  14. */
  15.  
  16. public class ImpatientProxy implements InvocationHandler {
  17. private Object obj;
  18.  
  19. /**
  20. Construct a dynamic proxy around the given object.
  21. @param obj the object to wrap
  22. @return the proxy
  23. */
  24.  
  25. public static Object newInstance(Object obj)
  26. {
  27. ClassLoader loader = obj.getClass().getClassLoader();
  28. Class[] classes = obj.getClass().getInterfaces();
  29. return Proxy.newProxyInstance(loader, classes, new ImpatientProxy(obj));
  30. }
  31. private ImpatientProxy(Object obj)
  32. {
  33. this.obj = obj;
  34. }
  35.  
  36. /**
  37. The method that all dynamic proxies must implement. This dynamic proxy
  38. complains when a method takes a long time to return.
  39. */
  40.  
  41. public Object invoke(Object proxy, Method m, Object[] args) throws Throwable
  42. {
  43. Object result;
  44. long t1 = System.currentTimeMillis();
  45. result = m.invoke(obj, args);
  46. long t2 = System.currentTimeMillis();
  47. if (t2 - t1 > 10) {
  48. System.out.println("> It takes " + (t2 - t1) + " millis to invoke " + m.getName() + "() with");
  49. for (int i = 0; i < args.length; i++)
  50. System.out.println("> arg[" + i + "]: " + args[i]);
  51. }
  52.  
  53. return result;
  54.  
  55. }
  56. }
Add Comment
Please, Sign In to add comment