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

动态代理。。。使用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();
}



无语了,红色的代码让我吃尽苦头。。。 在使用代理时,不可以在代理的实现中在使用代理来调用,不然就会不断地递归调用,知道堆栈溢出,最后崩溃。。。。

你可能感兴趣的:(java,.net)