java 动态代理实例详解
1.jdk动态代理
package com.sinosoft;
public interface Apple {
public void phoneCall();
}
package com.sinosoft;
public class AppleImpl implements Apple {
@Override
public void phoneCall() {
System.out.println("打电话");
}
}
package com.sinosoft;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class DynamicProxy implements InvocationHandler{
private Object object;
public DynamicProxy(Object object) {
this.object=object;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object result = method.invoke(object, args);
return result;
}
}
package com.sinosoft;
import java.lang.reflect.Proxy;
public class testDynamicProxy {
public static void main(String[] args) {
//1.创建接口的实现类
Apple tApple = new AppleImpl();
//2.动态代理类
DynamicProxy tDynamicProxy = new DynamicProxy(tApple);
ClassLoader tClassLoader = tApple.getClass().getClassLoader();
// 创建动态代理的对象,需要借助Proxy.newProxyInstance。该方法的三个参数分别是:
// ClassLoader loader表示当前使用到的appClassloader。
// Class>[] interfaces表示目标对象实现的一组接口。
// InvocationHandler h表示当前的InvocationHandler实现实例对象。
Apple apple = (Apple) Proxy.newProxyInstance(tClassLoader, new Class[] { Apple.class }, tDynamicProxy);
apple.phoneCall();
}
}
2.cglib动态代理
package com.sinosoft;
public class AppleClass{
public void phoneCall() {
System.out.println("打电话");
}
}
package com.sinosoft;
import java.lang.reflect.Method;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
public class CglibProxy implements MethodInterceptor{
@Override
public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
// TODO Auto-generated method stub
Object object= proxy.invokeSuper(obj, args);
return object;
}
}
package com.sinosoft;
import net.sf.cglib.proxy.Enhancer;
public class TestCglibProxy {
public static void main(String[] args) {
CglibProxy tCglibProxy=new CglibProxy();
Enhancer tEnhancer=new Enhancer();
tEnhancer.setSuperclass(AppleClass.class);
tEnhancer.setCallback(tCglibProxy);
AppleClass tApple= (AppleClass)tEnhancer.create();
tApple.phoneCall();
}
}
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!



