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");
}
}