好的,下面是基于类的动态代理示例代码:
```java
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import java.lang.reflect.Method;
public class UserService {
public void addUser(String username, String password) {
System.out.println("添加用户:" + username + ", 密码:" + password);
}
}
public class UserServiceProxy implements MethodInterceptor {
@Override
public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
System.out.println("开始执行方法:" + method.getName());
Object result = proxy.invokeSuper(obj, args);
System.out.println("方法执行完成:" + method.getName());
return result;
}
}
public class Main {
public static void main(String[] args) {
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(UserService.class);
enhancer.setCallback(new UserServiceProxy());
UserService userService = (UserService) enhancer.create();
userService.addUser("admin", "123456");
}
}
```
在上面的示例中,我们定义了一个UserService类。然后,我们创建了一个UserServiceProxy类来实现MethodInterceptor接口,并在其中添加了额外的逻辑,如打印日志等。最后,我们使用Enhancer类来创建代理对象,并将代理对象转换为UserService类型,从而实现了对UserService类的动态代理。