一. JDK动态代理示例
1. 接口
public interface UserService {
void addUser ( String name) ;
String getUser ( String name) ;
}
2. 被代理对象
public class UserServiceImpl implements UserService {
public void addUser ( String name) {
System. out. println ( "add user into database." ) ;
}
public String getUser ( String name) {
System. out. println ( "getUser from database." ) ;
return name;
}
}
3. 代理工具类
import java. lang. reflect. InvocationHandler;
import java. lang. reflect. Method;
import java. lang. reflect. Proxy;
public class ProxyUtil implements InvocationHandler {
private Object target ;
public Object getProxy ( Object targetObject) {
this . target = targetObject;
return Proxy. newProxyInstance ( targetObject. getClass ( ) . getClassLoader ( ) , targetObject. getClass ( ) . getInterfaces ( ) , this ) ;
}
public Object invoke ( Object proxy, Method method, Object[ ] args) throws Throwable {
System. out. println ( "JDK动态代理前置逻辑" ) ;
Object result = method. invoke ( target, args) ;
System. out. println ( "JDK动态代理后续逻辑" ) ;
return result;
}
}
4. 使用代理类
import java. lang. reflect. Proxy;
public class ProxyTest {
public static void main ( String[ ] args) {
UserServiceImpl userServiceImpl = new UserServiceImpl ( ) ;
UserService userService = ( UserService) new ProxyUtil ( ) . getProxy ( userServiceImpl) ;
userService. getUser ( "1" ) ;
userService. addUser ( "1" ) ;
}
}
5. 执行结果
JDK动态代理前置逻辑
getUser from database.
JDK动态代理后续逻辑
JDK动态代理前置逻辑
add user into database.
JDK动态代理后续逻辑
二. JDK动态代理说明
1. 获取代理对象:ProxyUtil.getProxy
2. 调用代理方法:ProxyUtil.invoke