您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
在Java中,拦截器(Interceptor)通常用于在方法调用前后执行一些操作,例如日志记录、权限检查等。要实现一个拦截器来进行日志记录,你可以使用Java的动态代理(Dynamic Proxy)或者第三方库(如Spring AOP)。
下面是一个使用Java动态代理实现日志记录拦截器的示例:
public interface MyInterface {
void doSomething();
}
public class MyInterfaceImpl implements MyInterface {
@Override
public void doSomething() {
System.out.println("MyInterfaceImpl: doSomething");
}
}
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class LoggingInterceptor implements InvocationHandler {
private Object target;
public LoggingInterceptor(Object target) {
this.target = target;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("Before method: " + method.getName());
Object result = method.invoke(target, args);
System.out.println("After method: " + method.getName());
return result;
}
}
import java.lang.reflect.Proxy;
public class Main {
public static void main(String[] args) {
MyInterface target = new MyInterfaceImpl();
LoggingInterceptor interceptor = new LoggingInterceptor(target);
MyInterface proxy = (MyInterface) Proxy.newProxyInstance(
target.getClass().getClassLoader(),
target.getClass().getInterfaces(),
interceptor
);
proxy.doSomething();
}
}
运行上述代码,你将看到以下输出:
Before method: doSomething
MyInterfaceImpl: doSomething
After method: doSomething
这样,你就实现了一个简单的日志记录拦截器。如果你使用Spring AOP,可以通过编写切面(Aspect)来实现类似的功能,会更加简洁和灵活。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。