Advertisement
Guest User

Untitled

a guest
Jul 17th, 2019
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.19 KB | None | 0 0
  1. package edu.mmc.proxy;
  2. import java.lang.reflect.InvocationHandler;
  3. import java.lang.reflect.Method;
  4. import java.lang.reflect.Proxy;
  5.  
  6. interface Human{
  7. String getBrief();
  8. void eat(String food);
  9. }
  10.  
  11. class SuperMan implements Human{
  12.  
  13. @Override
  14. public String getBrief() {
  15. return "I can fly";
  16. }
  17.  
  18. @Override
  19. public void eat(String food) {
  20. System.out.println("I like eat "+food);
  21. }
  22. }
  23.  
  24. class ProxyFactory{
  25. public static Object getProxyInstance(Object obj){
  26. MyInvocationHandler handler = new MyInvocationHandler();
  27. handler.bind(obj);
  28. return Proxy.newProxyInstance(obj.getClass().getClassLoader(),obj.getClass().getInterfaces(),handler);
  29. }
  30. }
  31.  
  32. class MyInvocationHandler implements InvocationHandler{
  33. private Object obj;
  34. public void bind(Object obj){
  35. this.obj = obj;
  36. }
  37. @Override
  38. public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
  39. return method.invoke(obj,args);
  40. }
  41. }
  42. public class ProxyTest {
  43. public static void main(String[] args) {
  44. SuperMan superMan = new SuperMan();
  45. Human proxy = (Human)ProxyFactory.getProxyInstance(superMan);
  46. proxy.eat("rice");
  47. }
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement