首页  

字节码增强cglib实例     所属分类 java 浏览量 1169
cglib Code Generation Library

cglib is a powerful, high performance and quality Code Generation Library, 
It is used to extend JAVA classes and implements interfaces at runtime.

cglib依赖 ASM库
ASM is a Java bytecode manipulation framework. 
It can be used to dynamically generate stub classes or other proxy classes,directly in binary form, 
or to dynamically modify classes at load time, just before they are loaded into the Java Virtual Machine.


字节码操作 字节码增强

Hibernate 利用cglib生成pojo子类并override get方法来实现lazy loading机制
Spring利用cglib来实现动态代理 
JDK动态代理机制基于接口

Enhancer生成原有类的子类,设置 callback , 方法调用时进行拦截
public  Object intercept(Object o,Method method,Object[] args,MethodProxy proxy)



简单例子 HelloProxyMain 

import java.lang.reflect.Method;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

public class HelloProxyMain {

	public static void main(String[] args) {

		Enhancer enhancer = new Enhancer();
		enhancer.setSuperclass(Hello.class);
		enhancer.setCallback(new MethodInterceptorImpl());
		Hello hello = (Hello) enhancer.create();
		hello.sayHello("dyyx");
		
		System.out.println(hello.toString());

	}

	private static class MethodInterceptorImpl implements MethodInterceptor {
		public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
			System.out.println(method + " run before ");
		    Object result = proxy.invokeSuper(obj, args);	
			System.out.println(method + " run after ,result="+result);
			return result;
		}
	}
}



经典的日志拦截 LogProxy import java.lang.reflect.Method; import net.sf.cglib.proxy.Enhancer; import net.sf.cglib.proxy.MethodInterceptor; import net.sf.cglib.proxy.MethodProxy; public class LogProxy implements MethodInterceptor { private Enhancer enhancer = new Enhancer(); public Object getObject(Class clz) { enhancer.setSuperclass(clz); enhancer.setCallback(this); return enhancer.create(); } public Object intercept(Object o, Method method, Object[] args, MethodProxy proxy) throws Throwable { System.out.println("log before method run," + method); Object result = proxy.invokeSuper(o, args); return result; } public static void main(String[] args) { LogProxy logProxy = new LogProxy(); Hello hello = (Hello) logProxy.getObject(Hello.class); hello.sayHello("tiger"); } } 完整的例子代码 https://gitee.com/dyyx/demos/tree/master/cglib

上一篇     下一篇
大数据风控概述

金融科技关键技术及应用

智能风控介绍

人类简史摘录

牛逼的蝙蝠

细菌病毒基因疾病科普