使用cglib中Enhancer在运行时根据某个给定的类创建子类
public class MsProxyBuilder { /** * 创建obj的代理对象 * @param obj 被代理对象 * @param interfaces 代理对象实现的接口数组 * @return 返回代理对象 */ public static Object buildProxy(Object obj, Class... interfaces) { if (obj == null || interfaces == null || interfaces.length == 0) { return obj; } Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(obj.getClass()); enhancer.setInterfaces(interfaces); MsMethodInterceptor methodInterceptor = new MsMethodInterceptor(); enhancer.setCallback(methodInterceptor); methodInterceptor.setTarget(obj); Object proxy = enhancer.create(); return proxy; }
}
public interface Message_t {} public interface IMessage {}
(IMessage) MsProxyBuilder.buildProxy(message, IMessage.class)