In learning to use CGlib to generate dynamic proxy objects, the source code of the project is also simple:
1 package proxy; 2 3 import java.lang.reflect.Method; 4 5 import net.sf.cglib.proxy.Enhancer; 6 import net.sf.cglib.proxy.MethodInterceptor; 7 import net.sf.cglib.proxy.MethodProxy; 8 9 public class CGlibProxy implements MethodInterceptor { 10 11 @SuppressWarnings("unchecked") 12 public <T> T getProxy(Class<T> clazz) { 13 return (T) Enhancer.create(clazz, this); 14 } 15 16 @Override 17 public Object intercept(Object obj, Method method, Object[] args, 18 MethodProxy proxy) throws Throwable { 19 before(); 20 Object result = proxy.invokeSuper(obj, args); 21 after(); 22 return result; 23 } 24 25 private void before() { 26 System.out.println(" before "); 27 28 } 29 30 private void after() { 31 System.out.println(" after "); 32 } 33 34 public static void main(String[] args) { 35 CGlibProxy cGlibProxy = new CGlibProxy(); 36 Hello helloProxy = cGlibProxy.getProxy(HelloImp.class); 37 helloProxy.say("Bob"); 38 39 } 40 }
Since CGlib is a third-party class library, the jar package version of CGlib is selected 2.2 to be introduced into the project path:
However, there were some abnormalities in operation:
Exception in thread "main" java.lang.NoClassDefFoundError: org/objectweb/asm/Type at net.sf.cglib.core.TypeUtils.parseType(TypeUtils.java:180) at net.sf.cglib.core.KeyFactory.<clinit>(KeyFactory.java:66) at net.sf.cglib.proxy.Enhancer.<clinit>(Enhancer.java:69) at proxy.CGlibProxy.getProxy(CGlibProxy.java:13) at proxy.CGlibProxy.main(CGlibProxy.java:36) Caused by: java.lang.ClassNotFoundException: org.objectweb.asm.Type at java.net.URLClassLoader$1.run(URLClassLoader.java:366) at java.net.URLClassLoader$1.run(URLClassLoader.java:355) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:354) at java.lang.ClassLoader.loadClass(ClassLoader.java:425) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308) at java.lang.ClassLoader.loadClass(ClassLoader.java:358) ... 5 more
Error reporting shows that there are classes that can not be found. Looking up the Internet, we know that many third-party class libraries for java bytecode operation and analysis are referenced. asm.jar Documents, because the project is not managed by Maven, can not solve the problem of transmission since, so we need to manually introduce asm.jar file. Add the asm.jar file to the project path class, run, and then it's normal.
Reference: http://javabeat.net/java-lang-noclassdeffounderror-orgobjectwebasm class visitor/