@DB() protected T toEntityBean(final ResultSet result, final boolean cache) throws SQLException { final T entity = (T) _factory.newInstance(new Callback[]{NoOp.INSTANCE, new UpdateBuilder(this)}); toEntityBean(result, entity); if (cache && _cache != null) { try { _cache.put(new Element(_idField.get(entity), entity)); } catch (final Exception e) { s_logger.debug("Can't put it in the cache", e); } } return entity; }
public void testSupportForClassBasedProxyWithAdditionalInterface() throws NullPointerException { final Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(HashMap.class); enhancer.setCallback(NoOp.INSTANCE); enhancer.setInterfaces(new Class[]{Runnable.class}); final Map orig = (Map)enhancer.create(); final String xml = "" + "<CGLIB-enhanced-proxy>\n" + " <type>java.util.HashMap</type>\n" + " <interfaces>\n" + " <java-class>java.lang.Runnable</java-class>\n" + " </interfaces>\n" + " <hasFactory>true</hasFactory>\n" + " <net.sf.cglib.proxy.NoOp_-1/>\n" + "</CGLIB-enhanced-proxy>"; final Object serialized = assertBothWays(orig, xml); assertTrue(serialized instanceof HashMap); assertTrue(serialized instanceof Map); assertTrue(serialized instanceof Runnable); }
public void testSupportsProxiesWithMultipleInterfaces() throws NullPointerException { final Enhancer enhancer = new Enhancer(); enhancer.setCallback(NoOp.INSTANCE); enhancer.setInterfaces(new Class[]{Map.class, Runnable.class}); final Map orig = (Map)enhancer.create(); final String xml = "" + "<CGLIB-enhanced-proxy>\n" + " <type>java.lang.Object</type>\n" + " <interfaces>\n" + " <java-class>java.util.Map</java-class>\n" + " <java-class>java.lang.Runnable</java-class>\n" + " </interfaces>\n" + " <hasFactory>true</hasFactory>\n" + " <net.sf.cglib.proxy.NoOp_-1/>\n" + "</CGLIB-enhanced-proxy>"; final Object serialized = assertBothWays(orig, xml); assertTrue(serialized instanceof Map); assertTrue(serialized instanceof Runnable); }
public void testSupportProxiesWithMultipleCallbackSetToNull() throws NullPointerException { final Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(HashMap.class); enhancer.setCallback(NoOp.INSTANCE); final HashMap orig = (HashMap)enhancer.create(); ((Factory)orig).setCallback(0, null); final String xml = "" + "<CGLIB-enhanced-proxy>\n" + " <type>java.util.HashMap</type>\n" + " <interfaces/>\n" + " <hasFactory>true</hasFactory>\n" + " <null/>\n" + "</CGLIB-enhanced-proxy>"; assertBothWays(orig, xml); }
public void testSupportsSerialVersionUID() throws NullPointerException, NoSuchFieldException, IllegalAccessException { final Enhancer enhancer = new Enhancer(); enhancer.setCallback(NoOp.INSTANCE); enhancer.setInterfaces(new Class[]{Runnable.class}); enhancer.setSerialVersionUID(new Long(20060804L)); final Runnable orig = (Runnable)enhancer.create(); final String xml = "" + "<CGLIB-enhanced-proxy>\n" + " <type>java.lang.Object</type>\n" + " <interfaces>\n" + " <java-class>java.lang.Runnable</java-class>\n" + " </interfaces>\n" + " <hasFactory>true</hasFactory>\n" + " <net.sf.cglib.proxy.NoOp_-1/>\n" + " <serialVersionUID>20060804</serialVersionUID>\n" + "</CGLIB-enhanced-proxy>"; final Object serialized = assertBothWays(orig, xml); final Field field = serialized.getClass().getDeclaredField("serialVersionUID"); field.setAccessible(true); assertEquals(20060804L, field.getLong(null)); }
public void testSupportsProxiesAsFieldMember() throws NullPointerException { ClassWithProxyMember expected = new ClassWithProxyMember(); xstream.alias("with-proxy", ClassWithProxyMember.class); final Enhancer enhancer = new Enhancer(); enhancer.setCallback(NoOp.INSTANCE); enhancer.setInterfaces(new Class[]{Map.class, Runnable.class}); final Map orig = (Map)enhancer.create(); expected.runnable = (Runnable)orig; expected.map = orig; final String xml = "" + "<with-proxy>\n" + " <runnable class=\"CGLIB-enhanced-proxy\">\n" + " <type>java.lang.Object</type>\n" + " <interfaces>\n" + " <java-class>java.util.Map</java-class>\n" + " <java-class>java.lang.Runnable</java-class>\n" + " </interfaces>\n" + " <hasFactory>true</hasFactory>\n" + " <net.sf.cglib.proxy.NoOp_-1/>\n" + " </runnable>\n" + " <map class=\"CGLIB-enhanced-proxy\" reference=\"../runnable\"/>\n" + "</with-proxy>"; final Object serialized = assertBothWays(expected, xml); assertTrue(serialized instanceof ClassWithProxyMember); }
@SuppressWarnings("unchecked") @DB() protected T toEntityBean(final ResultSet result, final boolean cache) throws SQLException { final T entity = (T)_factory.newInstance(new Callback[] {NoOp.INSTANCE, new UpdateBuilder(this)}); toEntityBean(result, entity); if (cache && _cache != null) { try { _cache.put(new Element(_idField.get(entity), entity)); } catch (final Exception e) { s_logger.debug("Can't put it in the cache", e); } } return entity; }
/** * Performs a benchmark of an interface implementation using cglib. * * @return The created instance, in order to avoid JIT removal. */ @Benchmark public ExampleInterface benchmarkCglib() { Enhancer enhancer = new Enhancer(); enhancer.setUseCache(false); enhancer.setClassLoader(newClassLoader()); enhancer.setSuperclass(baseClass); CallbackHelper callbackHelper = new CallbackHelper(Object.class, new Class[]{baseClass}) { @Override protected Object getCallback(Method method) { if (method.getDeclaringClass() == baseClass) { return new FixedValue() { @Override public Object loadObject() throws Exception { return null; } }; } else { return NoOp.INSTANCE; } } }; enhancer.setCallbackFilter(callbackHelper); enhancer.setCallbacks(callbackHelper.getCallbacks()); return (ExampleInterface) enhancer.create(); }
public Remote createServiceEndpoint() throws ServiceException { //TODO figure out why this can't be called in readResolve! // synchronized (this) { // if (!initialized) { // initialize(); // initialized = true; // } // } Service service = ((ServiceImpl) serviceImpl).getService(); GenericServiceEndpoint serviceEndpoint = new GenericServiceEndpoint(portQName, service, location); Callback callback = new ServiceEndpointMethodInterceptor(serviceEndpoint, sortedOperationInfos, credentialsName); Callback[] callbacks = new Callback[]{NoOp.INSTANCE, callback}; Enhancer.registerCallbacks(serviceEndpointClass, callbacks); try { return (Remote) constructor.newInstance(new Object[]{serviceEndpoint}); } catch (InvocationTargetException e) { throw (ServiceException) new ServiceException("Could not construct service instance", e.getTargetException()).initCause(e); } }
public static Class<?> getProxyClass(Class<?> clazz) { Enhancer e = new Enhancer(); if (clazz.isInterface()) { e.setSuperclass(clazz); } else { e.setSuperclass(clazz); e.setInterfaces(clazz.getInterfaces()); } e.setCallbackTypes(new Class[]{ InvocationHandler.class, NoOp.class, }); e.setCallbackFilter(BAD_OBJECT_METHOD_FILTER); e.setUseFactory(true); e.setNamingPolicy(new LithiumTestProxyNamingPolicy()); return e.createClass(); }
private static Object newProxyByCglib(Typing typing, Handler handler) { Enhancer enhancer = new Enhancer() { /** includes all constructors */ protected void filterConstructors(Class sc, List constructors) {} }; enhancer.setClassLoader(Thread.currentThread().getContextClassLoader()); enhancer.setUseFactory(true); enhancer.setSuperclass(typing.superclass); enhancer.setInterfaces(typing.interfaces.toArray(new Class[0])); enhancer.setCallbackTypes(new Class[] { MethodInterceptor.class, NoOp.class }); enhancer.setCallbackFilter(new CallbackFilter() { /** ignores bridge methods */ public int accept(Method method) { return method.isBridge() ? 1 : 0; } }); Class<?> proxyClass = enhancer.createClass(); Factory proxy = (Factory) new ObjenesisStd().newInstance(proxyClass); proxy.setCallbacks(new Callback[] { asMethodInterceptor(handler), new SerializableNoOp() }); return proxy; }
@Override protected Class<?> createProxyClass() { Enhancer en = new Enhancer(); en.setInterceptDuringConstruction(false); en.setUseFactory(true); en.setSuperclass(unproxiedClass); en.setInterfaces(new Class[] { Persistent.class }); en.setCallbackType(NoOp.class); en.setStrategy(new DefaultGeneratorStrategy() { protected ClassGenerator transform(ClassGenerator cg) throws Exception { return new TransformingClassGenerator(cg, new AddPropertyTransformer( new String[] { ORIGINAL_ONE, ORIGINAL_THE_OTHER }, new Type[] { Type.getType(String.class), Type.getType(List.class) } )); } }); return en.createClass(); }
static Map.Entry<Object, SetterInterceptor> getProxiedEntity(Class<?> entityClass) { EntityProxyFactory proxyFactory = getFactory(ClassHelper.actualClass(entityClass)); try { Object entity = null; SetterInterceptor interceptor = proxyFactory.new SetterInterceptor(); if (proxyFactory.isDistinguishable) { entity = proxyFactory.factory.newInstance(new Callback[] { interceptor, NoOp.INSTANCE }); } else { entity = proxyFactory.factory.newInstance(interceptor); } proxyFactory.modifiedPropNames.set(entity, new HashSet<String>()); interceptor.setEntity(entity); return new AbstractMap.SimpleEntry<Object, SetterInterceptor>(entity, interceptor); } catch (Throwable t) { throw new ODMException("Unable to instantiate proxy instance", t); } }
public T enhance(Class<T> clz) { Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(clz); enhancer.setCallbacks(new Callback[]{new PropertyInterceptor<>(this, schema), NoOp.INSTANCE}); enhancer.setCallbackFilter(new SchemaFilter<>(clz)); return (T) enhancer.create(); }
private void readCallback(final HierarchicalStreamReader reader, final UnmarshallingContext context, final List<Callback> callbacksToEnhance, final List<Callback> callbacks) { final Callback callback = (Callback)context.convertAnother(null, mapper.realClass(reader.getNodeName())); callbacks.add(callback); if (callback == null) { callbacksToEnhance.add(NoOp.INSTANCE); } else { callbacksToEnhance.add(callback); } }
private Object createCgLibProxy() { Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(Collection.class); enhancer.setCallback(new NoOp() { }); return enhancer.create(); }
/** * 代理某一个对象指定方法,并在这个方法执行前后加入新方法,可指定过滤掉非代理的方法 * @author nan.li * @param t * @param before 执行目标方法前要执行的方法 * @param after 执行目标方法后要执行的方法 * @return */ @SuppressWarnings("unchecked") public static <T> T proxySurround(T t, CustomMethod before, CustomMethod after, CallbackFilter callbackFilter) { MethodInterceptor methodInterceptor = new MethodInterceptor() { @Override public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable { before.execute(obj, method, args); Object result = null; try { result = proxy.invokeSuper(obj, args); } finally { after.execute(obj, method, args); } return result; } }; Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(t.getClass()); // 回调方法 // enhancer.setCallback(methodInterceptor); enhancer.setCallbacks(new Callback[] {methodInterceptor, NoOp.INSTANCE}); //NoOp回调把对方法的调用直接委派到这个方法在父类中的实现。 //Methods using this Enhancer callback ( NoOp.INSTANCE ) will delegate directly to the default (super) implementation in the base class. //setCallbacks中定义了所使用的拦截器,其中NoOp.INSTANCE是CGlib所提供的实际是一个没有任何操作的拦截器, 他们是有序的。一定要和CallbackFilter里面的顺序一致。 enhancer.setCallbackFilter(callbackFilter); // 创建代理对象 return (T)enhancer.create(); }
public ComponentInstantiationPostProcessor() { _callbacks = new Callback[2]; _callbacks[0] = NoOp.INSTANCE; _callbacks[1] = new InterceptorDispatcher(); _callbackFilter = new InterceptorFilter(); }
@SuppressWarnings("unchecked") public static <T> T create(Class<T> targetClass) throws InstantiationException, IllegalAccessException { Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(targetClass); enhancer.setClassLoader(targetClass.getClassLoader()); enhancer.setCallbackFilter(new TransactionalCallbackFilter()); Callback[] callbacks = new Callback[]{new DalTransactionInterceptor(), NoOp.INSTANCE}; enhancer.setCallbacks(callbacks); enhancer.setInterfaces(new Class[]{TransactionalIntercepted.class}); return (T)enhancer.create(); }
@Override protected Object getCallback(Method method) { if(method.getName().equals("name") && method.getReturnType().equals(String.class)) { return getNameCallback(); } if (method.getName().equals("getRealClassName") && method.getReturnType().equals(String.class)) { return getRealClassName(); } return NoOp.INSTANCE; }
public static Class getProxyFactory(Class persistentClass, Class[] interfaces) throws HibernateException { Enhancer e = new Enhancer(); e.setSuperclass( interfaces.length == 1 ? persistentClass : null ); e.setInterfaces(interfaces); e.setCallbackTypes(new Class[]{ InvocationHandler.class, NoOp.class, }); e.setCallbackFilter(FINALIZE_FILTER); e.setUseFactory(false); e.setInterceptDuringConstruction( false ); return e.createClass(); }
public Object getProxy() { try { return factory.newInstance( new Callback[] { new PassThroughInterceptor( proxyClass.getName() ), NoOp.INSTANCE } ); } catch ( Throwable t ) { throw new HibernateException( "Unable to instantiate proxy instance" ); } }
public void testSupportProxiesUsingFactoryWithMultipleCallbacks() throws NullPointerException { final Enhancer enhancer = new Enhancer(); enhancer.setCallbacks(new Callback[]{ new DelegatingInterceptor(null), new DelegatingHandler(null), new DelegatingDispatcher(null), NoOp.INSTANCE}); enhancer.setCallbackFilter(new CallbackFilter() { int i = 1; public int accept(Method method) { if (method.getDeclaringClass() == Runnable.class) { return 0; } return i < 3 ? i++ : i; } }); enhancer.setInterfaces(new Class[]{Runnable.class}); enhancer.setUseFactory(true); final Runnable orig = (Runnable)enhancer.create(); final String xml = xstream.toXML(orig); final Factory deserialized = (Factory)xstream.fromXML(xml); assertTrue("Not a Runnable anymore", deserialized instanceof Runnable); Callback[] callbacks = deserialized.getCallbacks(); assertEquals(4, callbacks.length); assertTrue(callbacks[0] instanceof DelegatingInterceptor); assertTrue(callbacks[1] instanceof DelegatingHandler); assertTrue(callbacks[2] instanceof DelegatingDispatcher); assertTrue(callbacks[3] instanceof NoOp); }
public void testThrowsExceptionForProxiesNotUsingFactoryWithMultipleCallbacks() throws NullPointerException { final Enhancer enhancer = new Enhancer(); enhancer.setCallbacks(new Callback[]{ new DelegatingInterceptor(null), new DelegatingHandler(null), new DelegatingDispatcher(null), NoOp.INSTANCE}); enhancer.setCallbackFilter(new CallbackFilter() { int i = 1; public int accept(Method method) { if (method.getDeclaringClass() == Runnable.class) { return 0; } return i < 3 ? i++ : i; } }); enhancer.setInterfaces(new Class[]{Runnable.class}); enhancer.setUseFactory(false); final Runnable orig = (Runnable)enhancer.create(); try { xstream.toXML(orig); fail("Thrown " + ConversionException.class.getName() + " expected"); } catch (final ConversionException e) { } }
public static TableDao getAuthInstance(AuthProxy authProxy) { Enhancer en=new Enhancer(); // Enhancer用来生成一个原有类的子类 // 进行代理 en.setSuperclass(TableDao.class); // 设置织入逻辑 // en.setCallback(authProxy); // en.setCallbacks()方法里的数组参数顺序就是上面方法的返回值所代表的方法拦截器,如果return 0则使用authProxy拦截器, // return 1则使用NoOp.INSTANCE拦截器,NoOp.INSTANCE是默认的方法拦截器,不做什么处理。 en.setCallbacks(new Callback[]{authProxy, NoOp.INSTANCE}); // 设置两个方法拦截器 en.setCallbackFilter(new AuthProxyFilter()); // 生成代理实例 return (TableDao)en.create(); }
private void readCallback(HierarchicalStreamReader paramHierarchicalStreamReader, UnmarshallingContext paramUnmarshallingContext, List paramList1, List paramList2) { Callback localCallback = (Callback)paramUnmarshallingContext.convertAnother(null, this.mapper.realClass(paramHierarchicalStreamReader.getNodeName())); paramList2.add(localCallback); if (localCallback == null) { paramList1.add(NoOp.INSTANCE); return; } paramList1.add(localCallback); }
@SuppressWarnings("unchecked") public <T> T getProxy(TypeToken<T> type) { Class<? super T> cls = type.getRawType(); if (isTerminal(type)) { return (T) Defaults.defaultValue(cls); } Enhancer e = new Enhancer(); if (Enhancer.isEnhanced(cls)) { e.setSuperclass(cls.getSuperclass()); e.setInterfaces(cls.getInterfaces()); } else { e.setSuperclass(cls); } e.setCallbackFilter(FINALIZE_FILTER); e.setCallbacks(new Callback[] { NoOp.INSTANCE, new MethodInterceptor() { @Override public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable { invocations.add(new MethodInvocation<Object>(type, method, Arrays.asList(args))); return getProxy(type.resolveType(method.getGenericReturnType())); } } }); try { return (T) e.create(); } catch (Exception ex) { throw new RuntimeException("Error while creating proxy of " + type, ex); } }
@SuppressWarnings("unchecked") private static <T> T proxyFor(Class<T> type) throws Exception { Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(TestCommand.class); enhancer.setCallbackType(NoOp.class); Class<T> enhanced = enhancer.createClass(); return enhanced.newInstance(); }
public void shouldDeProxyCGLibProxy() throws Exception { Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(ArrayList.class); enhancer.setCallbackTypes(new Class[] { NoOp.class }); Class<?> proxy = enhancer.createClass(); assertEquals(Types.deProxy(proxy), ArrayList.class); }
/** * Performs a benchmark for a trivial class creation using cglib. * * @return The created instance, in order to avoid JIT removal. */ @Benchmark public Class<?> benchmarkCglib() { Enhancer enhancer = new Enhancer(); enhancer.setUseCache(false); enhancer.setClassLoader(newClassLoader()); enhancer.setSuperclass(baseClass); enhancer.setCallbackType(NoOp.class); return enhancer.createClass(); }
private Class enhanceServiceEndpointInterface(Class serviceEndpointInterface, ClassLoader classLoader) { Enhancer enhancer = new Enhancer(); enhancer.setClassLoader(classLoader); enhancer.setSuperclass(GenericServiceEndpointWrapper.class); enhancer.setInterfaces(new Class[]{serviceEndpointInterface}); enhancer.setCallbackFilter(new NoOverrideCallbackFilter(GenericServiceEndpointWrapper.class)); enhancer.setCallbackTypes(new Class[]{NoOp.class, MethodInterceptor.class}); enhancer.setUseFactory(false); enhancer.setUseCache(false); return enhancer.createClass(); }
@Setup public void setUp() { for(int i = 0; i < COUNT; i++) { Enhancer enhancer = new Enhancer(); enhancer.setUseCache(false); // deactivate the cache to get a new instance each time enhancer.setCallbackType(NoOp.class); Class<?> c = enhancer.createClass(); toInstantiate[i] = c; } }
@Override public <T> T createProxy(Class<T> localizable, LocalizationProvider localizationProvider) { Method[] methods = localizable.getDeclaredMethods(); List<Callback> callbacks = new ArrayList<Callback>(methods.length + 1); final Map<Method, Integer> method2CallbackIndex = new HashMap<Method, Integer>(methods.length); callbacks.add(NoOp.INSTANCE); for (Method localizableMethod : methods) { callbacks.add(createCallback(localizationProvider, localizableMethod)); method2CallbackIndex.put(localizableMethod, callbacks.size() - 1); } CallbackFilter callbackFilter = new CallbackFilter() { @Override public int accept(Method method) { Integer index = method2CallbackIndex.get(method); return index == null ? 0 : index; } }; Enhancer enhancer = new Enhancer(); enhancer.setInterfaces(new Class[]{localizable}); enhancer.setCallbackFilter(callbackFilter); enhancer.setCallbacks(callbacks.toArray(new Callback[callbacks.size()])); enhancer.setUseFactory(false); @SuppressWarnings("unchecked") T instance = (T) enhancer.create(); return instance; }
public Object loadObject() throws Exception { try { Object result = ResultLoader.getResult(client, statementName, parameterObject, targetType); if (result == null) { // if no result is available return a proxy with a default object is returned // because the loadObject() method must not return null result = Enhancer.create(targetType, NoOp.INSTANCE); } return result; } catch (SQLException e) { throw new RuntimeException("Error lazy loading result. Cause: " + e, e); } }
@SuppressWarnings("unchecked") static <T> T getProxiedIndirections(T unproxied) { if (null == unproxied) { return null; } Class<?> actualClass = ClassHelper.actualClass(unproxied); OneMetaData oneMetaData = IndirectionsMetaData.get(actualClass).getOne(); TheOtherMetaData theOtherMetaData = IndirectionsMetaData.get(actualClass).getTheOther(); IndirectionsProxyFactory proxyFactory = getFactory(actualClass); try { T indirections = (T) proxyFactory.factory.newInstance(NoOp.INSTANCE); String originalOne = oneMetaData.getter().get(unproxied); List<String> originalTheOther = theOtherMetaData.getter().get(unproxied); proxyFactory.originalOne.set(indirections, originalOne); // make a copy, so that the coming changes will not impact it. proxyFactory.originalTheOther.set(indirections, new ArrayList<String>(originalTheOther)); oneMetaData.setter().set(indirections, originalOne); theOtherMetaData.setter().set(indirections, originalTheOther); return indirections; } catch (Throwable t) { throw new ODMException("Unable to instantiate proxy instance", t); } }
@Override protected Class<?> createProxyClass() { Enhancer en = new Enhancer(); en.setInterceptDuringConstruction(false); en.setUseFactory(true); en.setSuperclass(unproxiedClass); if (isDistinguishable(unproxiedClass)) { isDistinguishable = true; en.setInterfaces(new Class[] { Persistent.class, Distinguishable.class }); en.setCallbackTypes(new Class[] { MethodInterceptor.class, NoOp.class }); en.setCallbackFilter(FINALIZE_AND_DISTINGUISHABLE_INTEFERCE_FILTER); } else { en.setInterfaces(new Class[] { Persistent.class }); en.setCallbackType(SetterInterceptor.class); } // Add an additional track field. en.setStrategy(new DefaultGeneratorStrategy() { protected ClassGenerator transform(ClassGenerator cg) throws Exception { return new TransformingClassGenerator(cg, new AddPropertyTransformer( new String[] { MODIFIED_PROP_NAMES }, new Type[] { Type.getType(Set.class) } )); } }); return en.createClass(); }
static Object getLazyLoadingProxiedEntity(final Session session, final Class<?> entityClass, final String dn) { Object entity = null; if (isDistinguishable(entityClass)) { entity = Enhancer.create(entityClass, new Class[] { Persistent.class, Distinguishable.class }, FINALIZE_AND_DISTINGUISHABLE_INTEFERCE_FILTER, new Callback[] { new LazyLoader() { public Object loadObject() throws Exception { return session.read(entityClass, dn); } }, NoOp.INSTANCE } ); ((Distinguishable)entity).setDN(dn); } else { entity = Enhancer.create(entityClass, new Class[] { Persistent.class }, FINALIZE_FILTER, new Callback[] { new LazyLoader() { public Object loadObject() throws Exception { return session.read(entityClass, dn); } }, NoOp.INSTANCE } ); } return entity; }
/** * 代理一个对象<br> * 仅代理其列出的几个方法 * @author Administrator * @param t * @param before * @param after * @param methodNames * @return */ @SuppressWarnings("unchecked") public static <T> T proxySurroundIncludes(T t, CustomMethod before, CustomMethod after, String... methodNames) { MethodInterceptor methodInterceptor = new MethodInterceptor() { @Override public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable { before.execute(obj, method, args); Object result = null; try { result = proxy.invokeSuper(obj, args); } finally { after.execute(obj, method, args); } return result; } }; Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(t.getClass()); enhancer.setCallbacks(new Callback[] {methodInterceptor, NoOp.INSTANCE}); enhancer.setCallbackFilter(new CallbackFilter() { @Override public int accept(Method paramMethod) { //仅判断代理的情况 String name = paramMethod.getName(); if (ArrayUtils.contains(methodNames, name)) { return ProxyFlag.DO_PROXY.get(); } //默认不代理 return ProxyFlag.DO_NOT_PROXY.get(); } }); // 创建代理对象 return (T)enhancer.create(); }