直接上代码吧。
pom添加依赖:
<dependencies> <dependency> <groupId>cglib</groupId> <artifactId>cglib-nodep</artifactId> <version>3.1</version> </dependency> <dependency> <groupId>org.ow2.asm</groupId> <artifactId>asm</artifactId> <version>5.0.3</version> </dependency>
新建一个HelloWorld类:
package CglibTest.CglibTest; public class HelloWorld { public void sayHello(){ System.out.println("Hello world"); } }
然后是Main:
package CglibTest.CglibTest; import java.lang.reflect.Method; import net.sf.cglib.proxy.Enhancer; import net.sf.cglib.proxy.MethodInterceptor; import net.sf.cglib.proxy.MethodProxy; /** * Hello world! * */ public class App { public static void main( String[] args ) { Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(HelloWorld.class); enhancer.setCallback(new MyMethodInterceptor()); HelloWorld hw=(HelloWorld) enhancer.create(); hw.sayHello(); } } /* * */ class MyMethodInterceptor implements MethodInterceptor{ public Object intercept(Object arg0, Method arg1, Object[] arg2, MethodProxy arg3) throws Throwable { // TODO Auto-generated method stub System.out.println("before "+arg1.getName()+" "+arg2.length);//arg1是要调用的方法,arg2不知道是什么... Object o = arg3.invokeSuper(arg0,arg2);//看接口的说明arg0应该是指this System.out.println("after"); return o; } }
刚接触。。。代码跑起来了,也达到了预期的效果。。但是具体的东西还是不是很明白啊。
不过以后又多了一种创建对象的方式,不用new啊new的了。