jdk动态代理

 一、jdk动态代理demo

1、SayHelloService.java

 

/**
 * 
 * @author youli
 * 服务接口
 *
 */
public interface SayHelloService {
	public void service();
}

2、SayHelloServiceImpl.java

/**
 * 
 * @author youli
 * 被代理对象,实现了服务接口
 *
 */
public class SayHelloServiceImpl implements SayHelloService {

	@Override
	public void service() {
		System.out.println("Hello, world!!!");
	}

}

 

3、MyInvocationHandler.java

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
/**
 * 
 * @author youli
 * 调用拦截器,当调用代理对象的方法时,会调用invoke方法
 *
 */
public class MyInvocationHandler implements InvocationHandler {
	private Object target;//被代理对象,在invoke中使用
	
	public Object newInstance(Object target){
		this.target = target;
		//产生代理对象,也是实现了服务接口的子类
		return Proxy.newProxyInstance(target.getClass().getClassLoader(), 
				target.getClass().getInterfaces(), this);
	}

	@Override
	public Object invoke(Object arg0, Method arg1, Object[] arg2)
			throws Throwable {
		//arg0为代理对象
		System.out.println("started");
		arg1.invoke(target, arg2);
		System.out.println("ended");
		return null;
	}

}

 

4、JdkProxyTest.java

public class JdkProxyTest {

	public static void main(String[] args) {
		MyInvocationHandler myHandler = new MyInvocationHandler();
		SayHelloService sayHelloService = (SayHelloService)myHandler.newInstance(new SayHelloServiceImpl());
		sayHelloService.service();
	}

}

 

 5、输出结果

 

started

Hello, world!!!

ended

 

 二、cglib动态代理demo

1、SayHello.java

/**
 * 
 * @author youli
 *被代理类,无须实现服务接口
 */
public class SayHello {
	
	public void sayHello(){
		System.out.println("Hello, world!!!");
	}
}

 

2、MyMethodInterceptor.java

import java.lang.reflect.Method;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
/**
 * 
 * @author youli
 *拦截器类,当被代理对象被调用时,执行intercept方法
 */
public class MyMethodInterceptor implements MethodInterceptor {
	/**
	 * 
	 * @param clazz  被代理类
	 * @return 代理对象
	 */
	public Object newInstance(Class<?> clazz){
		Enhancer enhancer = new Enhancer();
		enhancer.setSuperclass(clazz);
		enhancer.setCallback(this);
		return enhancer.create();
	}

	@Override
	public Object intercept(Object object, Method method, Object[] args,
			MethodProxy proxy) throws Throwable {
		System.out.println("started");
		proxy.invokeSuper(object, args);//用invoke方法的话会出错
		System.out.println("ended");
		return null;
	}

}

 

3、CglibTest.java

public class CglibTest {

	public static void main(String[] args) {
		MyMethodInterceptor myMethodInterceptor = new MyMethodInterceptor();
		SayHello sayHello = (SayHello)myMethodInterceptor.newInstance(SayHello.class);
		sayHello.sayHello();
	}

}

 

4、输出结果:

started

Hello, world!!!

ended

 

 

 

 

 

 

你可能感兴趣的:(java动态代理demo)