https://www.zhihu.com/question/20794107

    1. public class Main {
    2. public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
    3. //People为接口
    4. //代理的对象User实现接口People
    5. //获得代理Class对象
    6. Class peopleProxyClass = Proxy.getProxyClass(People.class.getClassLoader(),People.class);
    7. //获得代理Class对象的构造器
    8. Constructor constructor = peopleProxyClass.getConstructor(InvocationHandler.class);
    9. //通过构造器获得代理对象
    10. People peopleImpl = (People)constructor.newInstance(new InvocationHandler() {
    11. //实现代理
    12. public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    13. //方法前的业务
    14. System.out.println("方法执行前");
    15. //user为代理对象
    16. User user = new User();
    17. //执行代理对象的原方法
    18. //通过InvocationHandler的实例调用
    19. Object result = method.invoke(user,args);
    20. //方法后的业务
    21. System.out.println("方法执行后");
    22. return result;
    23. }
    24. });
    25. //执行代理对象的方法
    26. peopleImpl.print();
    27. User user = new User();
    28. People people = (People) getProxy(user);
    29. people.print();
    30. }
    31. private static Object getProxy(final Object target) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
    32. Class peopleProxyClass = Proxy.getProxyClass(target.getClass().getClassLoader(),target.getClass().getInterfaces());
    33. Constructor constructor = peopleProxyClass.getConstructor(InvocationHandler.class);
    34. Object proxy = constructor.newInstance(new InvocationHandler() {
    35. public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    36. //方法前的业务
    37. System.out.println("方法执行前");
    38. //target为代理对象
    39. Object result = method.invoke(target,args);
    40. //方法后的业务
    41. System.out.println("方法执行后");
    42. return result;
    43. }
    44. });
    45. return proxy;
    46. }
    47. private static Object getProxy2(final Object target) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
    48. //使用newProxyInstance
    49. Object proxy = Proxy.newProxyInstance(
    50. target.getClass().getClassLoader(),
    51. target.getClass().getInterfaces(),
    52. new InvocationHandler() {
    53. public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    54. //方法前的业务
    55. System.out.println("方法执行前");
    56. //target为代理对象
    57. Object result = method.invoke(target,args);
    58. //方法后的业务
    59. System.out.println("方法执行后");
    60. return result;
    61. }
    62. });
    63. return proxy;
    64. }
    65. }