Java 动态代理实现

实现流程

1、代理对象
2、接口
3、目标对象

源码

  • 代理对象
package com.test;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class Main {
    public static void main(String[] args) {
        // 目标对象(委托对象)
        final UserServiceImpl target = new UserServiceImpl();
        // UserService 接口
        UserService service = (UserService) Proxy.newProxyInstance(Main.class.getClassLoader(), new Class[]{UserService.class}, new InvocationHandler() {
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                System.out.println("执行前");
                Object result = method.invoke(target, args);
                System.out.println("执行后");
                return result;
            }
        });

        System.out.println(service.getAge());
    }
}
  • UserService 接口
package com.test;

public interface UserService {

    Boolean isAdult();

    Integer getAge();
}
  • UserServiceImpl 接口实现类
package com.test;

public class UserServiceImpl implements UserService {
    public Boolean isAdult() {
        return false;
    }

    public Integer getAge() {
        return 18;
    }
}

你可能感兴趣的:(JAVA)