不想说了。。 代理,动态代理

动态代理。。。使用cglib 这个jar文件。。

package test.dynasic;

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 TestDynasicProxy implements MethodInterceptor {

@Override
public Object intercept(Object proxy, Method method, Object[] args,
MethodProxy methodProxy) throws Throwable {
System.out.println("before method invoke " + method.getName());
[color=red]Object o = methodProxy.invokeSuper(proxy, args);[/color]
System.out.println("after method invoke ");
return o;
}

public static void main(String[]args){
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(DynasicProxy.class);
enhancer.setCallback(new TestDynasicProxy());
DynasicProxy dp = (DynasicProxy)enhancer.create();
dp.saySomething();
}

}


class DynasicProxy{
public void saySomething(){
System.out.println("hello");
}
}


java中的反射机制实现的代理,适合实现接口的类


package test;

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

public class TestProxy {
public static void main(String[]args){
IProxy myProxy = (IProxy) Proxy.newProxyInstance(MyProxy.class.getClassLoader(), MyProxy.class.getInterfaces(), new MyProxyHandler<IProxy>(new MyProxy()));
String message = myProxy.saySomething();
System.out.println(message);
}
}


class MyProxy implements IProxy {
public String saySomething(){
System.out.println("hello");
return "ok";
}
}

class MyProxyHandler<T> implements InvocationHandler{
private T t;

public MyProxyHandler(T t){
this.t = t;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {

Object returnMessage = null;
try{
System.out.println("before method invoke "+method.getName());
[color=red]returnMessage = method.invoke(t, args);[/color]
System.out.println(returnMessage);
System.out.println("after method invoke");
} catch(Exception e){
e.printStackTrace();
}
return returnMessage;
}

}


接口:

package test;

interface IProxy {
public String saySomething();
}



无语了,红色的代码让我吃尽苦头。。。 在使用代理时,不可以在代理的实现中在使用代理来调用,不然就会不断地递归调用,知道堆栈溢出,最后崩溃。。。。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值