JDK Proxy实现接口代理

JDK提供的java.reflect.Proxy代理类提供基于接口代理功能,由Proxy.newProxyInstance(ClassLoader interfaceClassLoader,Class<?>[] interfaces, InvocationHandler handler)创建的对象属于java.reflect.Proxy实例,由于Java中只能实现单继承,所以无法对类进行代理。生成的类默认重载了java.lang.Object的hashCode、toString、equals方法,所以调用proxy.hashCode也会间接的调用Proxy的InvoctionHandler的实现。

若要对类进行代理,可以考虑采用CGLIB为类生成动态功能。

以下是JDK Proxy实现接口代理的功能代码:

1、被代理接口定义

package zd.proxy;

/**
 * 用户操作Bean。
 * @author jim
 *
 */
public interface UserDao {
		
		/***
		 * 插入用户。
		 * @param user User
		 */
		void insert(String user);
}

package zd.proxy;

public interface PersonDao {
		void call();
}

2、执行处理器

package zd.proxy;

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

import static java.lang.System.out;


/**
 * Proxy执行处理器,此类无状态,单例。
 * @author jim
 *
 */
public class JdkProxyInvocationHandler implements InvocationHandler {
	private static JdkProxyInvocationHandler instance= null;
	
	/** 私有构造器 */
	private JdkProxyInvocationHandler() {
	}
	
	@Override
	public Object invoke(Object target, Method targetMethod, Object[] params)
			throws Throwable {
			
			// Proxy示例实现了提供的所有接口,并继承自Proxy
			out.println(target instanceof UserDao); // true
			out.println(target instanceof Proxy); // true
			out.println(target instanceof PersonDao); // true
			out.println(params[0]); // sss
			return null;
	}
	
	/**
	 * 获取该类实例
	 * @return
	 */
	public static JdkProxyInvocationHandler getInstance(){
			if (instance == null){
					initInstance();
			}
		
			return instance;
	}
	
	/**
	 * 初始化示例。
	 */
	private static synchronized void initInstance(){
			if (instance == null){
				  instance = new JdkProxyInvocationHandler();
			}
	}
}
3、代理创建与接口调用测试。

package zd.proxy;

import java.lang.reflect.Proxy;

import org.junit.Test;

/**
 * JDK Proxy测试,采用JUnit。
 * @author jim
 *
 */
public class JdkProxy {

		/**
		 * 测试接口代理。
		 */
		@Test
		public void testInterface(){
				
			UserDao proxy = (UserDao)Proxy.newProxyInstance(UserDao.class.getClassLoader(), new Class[]{UserDao.class,PersonDao.class},
						JdkProxyInvocationHandler.getInstance());
			
			proxy.insert("ssss");
		}
}



评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值