当前位置:网站首页>Cglib agent - Code enhancement test
Cglib agent - Code enhancement test
2022-07-02 06:22:00 【One eyebrow procedural ape】
Guide pack
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>3.3.0</version>
</dependency>
Write method interceptors
- Method to enhance specific logic
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import java.lang.reflect.Method;
import java.util.Arrays;
/** * Customize cglib agent * * @author Ara * @since 2022/6/20 */
public class MyCglibProxyMethodInterceptor<T> implements MethodInterceptor {
/** * Target audience */
private final T target;
/** * Construction method */
public MyCglibProxyMethodInterceptor(T target) {
this.target = target;
}
/** * Get proxy object */
public T getProxyObject(){
Enhancer enhancer = new Enhancer();
// Set parent class because cglib Is to generate a subclass for the specified class to enhance its behavior
enhancer.setSuperclass(target.getClass());
enhancer.setCallback(this);
return (T) enhancer.create();
}
// TODO Perform the enhancement
@Override
public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
System.out.println(" Before execution Method parameter : " + Arrays.toString(objects));
Object result = method.invoke(target, objects);
System.out.println(" After execution Return value : " + result);
return result;
}
}
Write the test class to be enhanced
- Enhance target points
/** * article Service * * @author Ara * @since 2022/6/20 */
public class ArticleService {
public String saveArticle(String article) {
System.out.printf(" Save the article [%s]...%n", article);
return article;
}
}
Write tests
- Check whether it can be enhanced
public class MainTest {
public static void main(String[] args) {
ArticleService articleService = new ArticleService();
// Statement Cglib Method intercept enhanced implementation class
MyCglibProxyMethodInterceptor<ArticleService> cglibProxyMethodInterceptor = new MyCglibProxyMethodInterceptor<>(articleService);
// Get proxy class
ArticleService articleServiceProxy = cglibProxyMethodInterceptor.getProxyObject();
// Use proxy classes to call methods
articleServiceProxy.saveArticle("Java");
}
}
The verification results

A small summary
Simple comparison cglib And JDK A dynamic proxy :
- Use here cglib When acting , Whether or not the target class implements the interface , Can be enhanced .
- But when used alone JDK A dynamic proxy , You can only enhance the methods of class overrides that implement interfaces .
The following is right cglib and JDK Whether dynamic proxy can enhance the comparison code of classes with and without interface implementation , Interested readers can test :
public class MainTest {
public static void main(String[] args) {
cglibProxyNoInterfaceTest();
}
/** * cglib agent ( Proxy target class does not implement interface ) */
private static void cglibProxyNoInterfaceTest(){
ArticleService articleService = new ArticleService();
// Statement Cglib Method intercept enhanced implementation class
MyCglibProxyMethodInterceptor<ArticleService> cglibProxyMethodInterceptor = new MyCglibProxyMethodInterceptor<>(articleService);
// Get proxy class
ArticleService articleServiceProxy = cglibProxyMethodInterceptor.getProxyObject();
// Use proxy classes to call methods
articleServiceProxy.saveArticle("Java");
}
/** * cglib agent ( The proxy target class implements the interface ) */
private static void cglibProxyHasInterfaceTest(){
UserService userService = new UserServiceImpl();
// Statement Cglib Method intercept enhanced implementation class
MyCglibProxyMethodInterceptor<UserService> cglibProxyMethodInterceptor = new MyCglibProxyMethodInterceptor<>(userService);
// Get proxy class
UserService userServiceProxy = cglibProxyMethodInterceptor.getProxyObject();
// Use proxy classes to call methods
userServiceProxy.add("Ara");
}
/** * JDK A dynamic proxy ( The proxy target class implements the interface ) */
private static void jdkDynamicProxyHasInterfaceTest(){
// The original object ( Interface receive parameters )
UserService userService = new UserServiceImpl();
// Declare enhanced handlers
MyJdkProxyInvocationHandler<UserService> proxyInvocationHandler = new MyJdkProxyInvocationHandler<>(userService);
// Get proxy object
UserService proxyUserService = proxyInvocationHandler.getProxyObject();
// Use proxy objects to call methods
proxyUserService.add("Ara");
}
/** * JDK A dynamic proxy ( Proxy target class does not implement interface ) * Mistake , Use JDK Dynamic proxy implementation enhancements , The proxy target must be required to implement the interface */
private static void jdkDynamicProxyNoInterfaceTest(){
ArticleService articleService = new ArticleService();
// Declare enhanced handlers
MyJdkProxyInvocationHandler<ArticleService> proxyInvocationHandler = new MyJdkProxyInvocationHandler<>(articleService);
// Get proxy object
ArticleService proxyArticleService = proxyInvocationHandler.getProxyObject();
// Use proxy objects to call methods
proxyArticleService.saveArticle("Java");
}
}
边栏推荐
猜你喜欢

阿里云MFA绑定Chrome浏览器

Find the highest value of the current element Z-index of the page

Hydration failed because the initial UI does not match what was rendered on the server. One of the reasons for the problem

sudo提权

Linear DP (split)

The official zero foundation introduction jetpack compose Chinese course is coming!
![Data science [viii]: SVD (I)](/img/cb/7bf066a656d49666985a865c3a1456.png)
Data science [viii]: SVD (I)

ShardingSphere-JDBC篇

AttributeError: ‘str‘ object has no attribute ‘decode‘

一口气说出 6 种实现延时消息的方案
随机推荐
【每日一题】写一个函数,判断一个字符串是否为另外一个字符串旋转之后的字符串。
一口气说出 6 种实现延时消息的方案
LeetCode 40. Combined sum II
IDEA公布全新默认UI,太清爽了(内含申请链接)
The real definition of open source software
BGP routing optimization rules and notification principles
I/o impressions from readers | prize collection winners list
Amazon AWS data Lake Work Pit 1
RestTemplate请求时设置请求头,请求参数,请求体。
CUDA中内置的Vector类型和变量
BGP 路由優選規則和通告原則
Data science [viii]: SVD (I)
LeetCode 83. 删除排序链表中的重复元素
LeetCode 47. Full arrangement II
Database learning summary 5
深入学习JVM底层(二):HotSpot虚拟机对象
Data science [9]: SVD (2)
Use of Arduino wire Library
In depth understanding of JUC concurrency (I) what is JUC
Reading classic literature -- Suma++