Java动态代理与CGLib

Java动态代理机制是一种强大的编译时生成代码的机制。
比如以下例子,其实就是在编译后生成一个HelloImpl的代理类。它要求被代理的方法必须来自于一个借口,如例子中的Hello

package org.mark.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class TestDynamicProxy {
public static interface Hello {
public void sayHello();
}

public static class HelloImpl implements Hello {

@Override
public void sayHello() {
// TODO Auto-generated method stub
System.out.println("say hello");
}

}

public static class ProxyTest implements InvocationHandler {
Object originalObj;

Object bind(Object originalObj) {
this.originalObj = originalObj;

return Proxy.newProxyInstance(originalObj.getClass().getClassLoader(), originalObj.getClass().getInterfaces(), this);
}

@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
System.out.println("DynamicProxy invocated!");
return method.invoke(originalObj, args);
}

}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Hello hello = (Hello) new ProxyTest().bind(new HelloImpl());
hello.sayHello();
}

}


那么问题来了,挖掘机技术哪家强?

如果说一个普通的类,有一个方法,该方法并非实现接口所得,那么它的动态代理应该怎么做呢?首先Java的JDK内置动态代理无法做到,因为它要求代理的方法必须来自于借口,所以可以用CGLib来做此类的代理行为。CGLIB具有简单易用,它的运行速度要远远快于JDK的Proxy动态代理。

如下例子程序

package org.mark.proxy;

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 TestCGLib {
public static class InfoManager {
public void create() {
System.out.println("Create a record");
}
}

public static class InfoManagerFactory {
public static InfoManager getInstance(CGLibProxy proxy) {
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(InfoManager.class);
enhancer.setCallback(proxy);
return (InfoManager)enhancer.create();
}
}

public static class CGLibProxy implements MethodInterceptor {
private String name;

public CGLibProxy(String name) {
this.name = name;
}

@Override
public Object intercept(Object arg0, Method arg1, Object[] arg2,
MethodProxy arg3) throws Throwable {
if(!name.equals("Test")) {
System.out.println("Name is not Test, cglib ignored");
return null;
}
System.out.println("cglib proxy called");
return arg3.invokeSuper(arg0, arg2);
}

}

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
InfoManager manager = InfoManagerFactory.getInstance(new CGLibProxy("Test"));
manager.create();

InfoManager manager2 = InfoManagerFactory.getInstance(new CGLibProxy("Test2"));
manager2.create();
}

}

你可能感兴趣的:(Core,Java,Framework,CGLib)