public static Object createProxy(Object realObject) { try { MethodInterceptor interceptor = new HammerKiller(); Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(realObject.getClass()); enhancer.setCallbackType(interceptor.getClass()); Class classForProxy = enhancer.createClass(); Enhancer.registerCallbacks(classForProxy, new Callback[]{interceptor}); Object createdProxy = classForProxy.newInstance(); for (Field realField : FieldUtils.getAllFieldsList(realObject.getClass())) { if (Modifier.isStatic(realField.getModifiers())) continue; realField.setAccessible(true); realField.set(createdProxy, realField.get(realObject)); } CreeperKiller.LOG.info("Removed HammerCore main menu hook, ads will no longer be displayed."); return createdProxy; } catch (Exception e) { CreeperKiller.LOG.error("Failed to create a proxy for HammerCore ads, they will not be removed.", e); } return realObject; }
/** * 生成代理对象 * @param targetClass 被代理对象的类型(类或接口) * @param target 被代理对象实例 * @return 代理对象 */ @SuppressWarnings("unchecked") public <T> T newProxyInstance(final Class<T> targetClass, final Object target) { return (T) Enhancer.create(targetClass, new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { before(targetClass, method, args); Object ret = null; try { ret = method.invoke(target, args); } catch (Exception e) { exception(targetClass, method, args, e); } after(targetClass, method, args); return ret; } }); }
@Override @SuppressWarnings("unchecked") public <T> T newProxyInstance(final Class<T> targetClass, final Object target) { return (T) Enhancer.create(targetClass, new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { /** * 如果没有@Transaction,则直接调用原方法 */ if (!method.isAnnotationPresent(Transaction.class)) { return method.invoke(target, args); } before(targetClass, method, args); Object ret = null; try { ret = method.invoke(target, args); } catch (Exception e) { exception(targetClass, method, args, e); } after(targetClass, method, args); return ret; } }); }
ReflectiveParserImpl(Class<?> base, List<Property<?, ?>> properties) { InjectionChecks.checkInjectableCGLibProxyBase(base); this.properties = properties; this.propertyNames = properties.stream() .flatMap(property -> property.parser.names().stream()) .collect(Collectors.toImmutableSet()); final Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(base); enhancer.setInterfaces(new Class[]{ type.getRawType() }); enhancer.setCallbackType(MethodInterceptor.class); enhancer.setUseFactory(true); this.impl = enhancer.createClass(); this.injector = getMembersInjector((Class<T>) impl); }
public static Factory getProxyFactory(Class persistentClass, Class[] interfaces) throws HibernateException { //note: interfaces is assumed to already contain HibernateProxy.class try { return (Factory) Enhancer.create( (interfaces.length==1) ? persistentClass : null, interfaces, NULL_METHOD_INTERCEPTOR ); } catch (Throwable t) { LogFactory.getLog(LazyInitializer.class).error("CGLIB Enhancement failed", t); throw new HibernateException( "CGLIB Enhancement failed", t ); } }
/** * 使用 cglib 库创建 JedisProxy 的代理对象 * * @return JedisProxy 代理 */ public JedisProxy getJedisProxy() { if (jedisProxy != null) { return jedisProxy; } synchronized (JedisMethodInterceptor.class) { if (jedisProxy != null) { return jedisProxy; } Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(JedisProxy.class); enhancer.setCallback(this); jedisProxy = (JedisProxy) enhancer.create(); } return jedisProxy; }
public ConstructionProxy<T> create() throws ErrorsException { if (interceptors.isEmpty()) { return new DefaultConstructionProxyFactory<T>(injectionPoint).create(); } @SuppressWarnings("unchecked") Class<? extends Callback>[] callbackTypes = new Class[callbacks.length]; for (int i = 0; i < callbacks.length; i++) { if (callbacks[i] == net.sf.cglib.proxy.NoOp.INSTANCE) { callbackTypes[i] = net.sf.cglib.proxy.NoOp.class; } else { callbackTypes[i] = net.sf.cglib.proxy.MethodInterceptor.class; } } // Create the proxied class. We're careful to ensure that all enhancer state is not-specific // to this injector. Otherwise, the proxies for each injector will waste PermGen memory try { Enhancer enhancer = BytecodeGen.newEnhancer(declaringClass, visibility); enhancer.setCallbackFilter(new IndicesCallbackFilter(methods)); enhancer.setCallbackTypes(callbackTypes); return new ProxyConstructor<T>(enhancer, injectionPoint, callbacks, interceptors); } catch (Throwable e) { throw new Errors().errorEnhancingClass(declaringClass, e).toException(); } }
/** * Adds transaction support to the page. The transaction support captures execution time of methods annotated with * {@link io.devcon5.pageobjects.tx.Transaction} * * @param <T> * * @param transactionSupport * the transactionSupport element to be enhanced. * @return */ @SuppressWarnings("unchecked") public static <T extends TransactionSupport> T addTransactionSupport(TransactionSupport transactionSupport) { return (T) Enhancer.create(transactionSupport.getClass(), (MethodInterceptor) (obj, method, args, proxy) -> { final Optional<String> txName = getTxName(transactionSupport, method); try { txName.ifPresent(transactionSupport::txBegin); Object result = method.invoke(transactionSupport, args); //dynamically enhance return values, if they are transactionSupport and not yet enhanced //this is required, i.e. if method return 'this' or create new objects which will //not be enhanced if (!isCGLibProxy(result) && result instanceof TransactionSupport) { result = addTransactionSupport(transactionSupport); } return result; } finally { txName.ifPresent(transactionSupport::txEnd); } }); }
public static void main(String[] args) { while(true) { Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(ClassPermGenOOM.class); enhancer.setUseCache(Boolean.FALSE); enhancer.setCallback(new MethodInterceptor() { @Override public Object intercept(Object arg0, Method arg1, Object[] arg2, MethodProxy arg3) throws Throwable { return arg3.invokeSuper(arg0, arg2); } }); enhancer.create(); } }
public static <T> T cglibcreate(T o, OrientElement oe, Transaction transaction ) { // this is the main cglib api entry-point // this object will 'enhance' (in terms of CGLIB) with new capabilities // one can treat this class as a 'Builder' for the dynamic proxy Enhancer e = new Enhancer(); // the class will extend from the real class e.setSuperclass(o.getClass()); // we have to declare the interceptor - the class whose 'intercept' // will be called when any method of the proxified object is called. ObjectProxy po = new ObjectProxy(o.getClass(),oe, transaction); e.setCallback(po); e.setInterfaces(new Class[]{IObjectProxy.class}); // now the enhancer is configured and we'll create the proxified object T proxifiedObj = (T) e.create(); po.___setProxyObject(proxifiedObj); // the object is ready to be used - return it return proxifiedObj; }
public static <T> T cglibcreate(Class<T> c, OrientElement oe, Transaction transaction ) { // this is the main cglib api entry-point // this object will 'enhance' (in terms of CGLIB) with new capabilities // one can treat this class as a 'Builder' for the dynamic proxy Enhancer e = new Enhancer(); // the class will extend from the real class e.setSuperclass(c); // we have to declare the interceptor - the class whose 'intercept' // will be called when any method of the proxified object is called. ObjectProxy po = new ObjectProxy(c,oe, transaction); e.setCallback(po); e.setInterfaces(new Class[]{IObjectProxy.class}); // now the enhancer is configured and we'll create the proxified object T proxifiedObj = (T) e.create(); po.___setProxyObject(proxifiedObj); // the object is ready to be used - return it return proxifiedObj; }
public static void main(String[] args) { Tmp tmp = new Tmp(); while (!Thread.interrupted()) { Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(Tmp.class); enhancer.setUseCache(false); enhancer.setCallback(new MethodInterceptor() { @Override public Object intercept(Object arg0, Method arg1, Object[] arg2, MethodProxy arg3) throws Throwable { return arg3.invokeSuper(arg0, arg2); } }); enhancer.create(); } System.out.println(tmp.hashCode()); }
/** * Wraps the specified API object to dump caller stacktraces right before invoking * native methods * * @param api API * @return wrapped API */ static <T> T wrapWithCrashStackLogging(final Class<T> apiClazz, final T api) { try { return AccessController.doPrivileged(new PrivilegedExceptionAction<T>() { @Override public T run() throws Exception { MethodInterceptor handler = new MethodInterceptorWithStacktraceLogging<T>(api); T wrapperWithStacktraceLogging = (T) Enhancer.create(apiClazz, handler); return wrapperWithStacktraceLogging; } }); } catch (PrivilegedActionException e) { e.printStackTrace(); return api; } }
@SuppressWarnings("unchecked") public T decode(final BitBuffer buffer, final Resolver resolver, final Builder builder) throws DecodingException { final int size = wrapped.getSize().eval(resolver); final long pos = buffer.getBitPos(); ClassLoader loader = this.getClass().getClassLoader(); Enhancer enhancer = new Enhancer(); enhancer.setClassLoader(loader); enhancer.setSuperclass(type); enhancer.setCallback(new MethodInterceptor() { private Object actual; public Object intercept(Object target, Method method, Object[] args, MethodProxy proxy) throws Throwable { if (actual == null) { buffer.setBitPos(pos); actual = wrapped.decode(buffer, resolver, builder); } return proxy.invoke(actual, args); } }); buffer.setBitPos(pos + size); return (T) enhancer.create(); }
public Object proxy() { Optional<Class> genericClassCollection = ReflectionUtils.getGenericClassCollection(fieldOrigin); if (!genericClassCollection.isPresent()) { throw new IllegalArgumentException("Invalid collection on field [" + fieldOrigin.getName() + "]"); } Boolean hasPrimitive = PrimitiveTypeFields.getInstance().contains(genericClassCollection.get()); if (hasPrimitive) { return hibernateCollection; } else { return this.hibernateCollection.stream() .map(item -> Enhancer.create(genericClassCollection.get(), ProxyInterceptor.create(item)) ).collect(Collectors.toList()); } }
@SuppressWarnings("unchecked") protected static <T> Class<T> createEnhancedClass(Class<T> proxiedClass, Class<?>... implementedInterfaces) { Enhancer enhancer = new Enhancer(); Set<Class<?>> interfaces = new HashSet<Class<?>>(); if (proxiedClass.isInterface()) { enhancer.setSuperclass(Object.class); interfaces.add(proxiedClass); } else { enhancer.setSuperclass(proxiedClass); } if (implementedInterfaces != null && implementedInterfaces.length > 0) { interfaces.addAll(asList(implementedInterfaces)); } if (!interfaces.isEmpty()) { enhancer.setInterfaces(interfaces.toArray(new Class<?>[interfaces.size()])); } enhancer.setCallbackType(MethodInterceptor.class); enhancer.setUseFactory(true); return enhancer.createClass(); }
@Override public Jedis getResource() { // add a simplistic retry strategy so we don't fail on the occasional pool timeout Jedis resource = null; try { resource= super.getResource(); } catch (RuntimeException e) { try { Thread.sleep(500); // give it half a second to recover } catch (InterruptedException ex) { throw new IllegalStateException(ex); } try { resource= super.getResource(); poolRetryCounter.inc(); } catch (RuntimeException e2) { LOG.error("redis connect failure after retry once. Host: '" + redisHost + "' port: '" + redisPort + "' redis db: '" + redisDatabase + "' redis password: '" + redisPassword +"'"); poolFailCounter.inc(); // rethrow and let things escalate throw e2; } } return (Jedis) Enhancer.create(Jedis.class, new MeasuringJedisHandler(resource)); }
@Override public Object postProcessBeforeInstantiation(final Class<?> beanClass, final String beanName) throws BeansException { if (_interceptors != null && _interceptors.size() > 0) { if (ComponentMethodInterceptable.class.isAssignableFrom(beanClass)) { final Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(beanClass); enhancer.setCallbacks(getCallbacks()); enhancer.setCallbackFilter(getCallbackFilter()); enhancer.setNamingPolicy(ComponentNamingPolicy.INSTANCE); final Object bean = enhancer.create(); return bean; } } return null; }
/** * Build CGLIB <i>implementee</i> bean. * * @param implementation * @param implementorBeanFactory * @return */ protected Object doBuild( Implementation<?> implementation, ImplementorBeanFactory implementorBeanFactory) { InvocationHandler invocationHandler = new CglibImplementeeInvocationHandler( implementation, implementorBeanFactory, implementeeMethodInvocationFactory); Enhancer enhancer = new Enhancer(); enhancer.setInterfaces(new Class[] { CglibImplementee.class }); enhancer.setSuperclass(implementation.getImplementee()); enhancer.setCallback(invocationHandler); return enhancer.create(); }
@Override public <T> T createDynamicProxy(Class<T> type, Supplier<T> targetSupplier, String descriptionPattern, Object... descriptionParams) { final String description = String.format(descriptionPattern, descriptionParams); final Enhancer enhancer = new Enhancer(); enhancer.setClassLoader(new DelegatingClassLoader(type.getClassLoader(), Enhancer.class.getClassLoader())); enhancer.setInterfaces(new Class[]{type}); enhancer.setSuperclass(Object.class); enhancer.setCallbackFilter(FILTER); enhancer.setCallbacks(new Callback[]{ (Dispatcher) targetSupplier::get, (MethodInterceptor) (proxy, method, params, methodProxy) -> proxy == params[0], (MethodInterceptor) (proxy, method, params, methodProxy) -> System.identityHashCode(proxy), (MethodInterceptor) (proxy, method, params, methodProxy) -> description }); return type.cast(enhancer.create()); }
private ServletWebRequest getSuperPoweredRequest(ServletWebRequest request, HttpServletRequest superPoweredMockRequest) { if (isSuperPowered(request)) { return request; } Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(SingularServletWebRequest.class); enhancer.setInterfaces(new Class[]{SuperPowered.class}); enhancer.setCallback(new InvocationHandler() { @Override public Object invoke(Object o, Method method, Object[] objects) throws InvocationTargetException, IllegalAccessException { if ("getContainerRequest".equals(method.getName())) { return superPoweredMockRequest; } return method.invoke(request, objects); } }); return (ServletWebRequest) enhancer.create(); }
public NaviDataServiceProxy(IBaseDataService realService, Class<?> inter) { this.realService = realService; Class<?>[] inters = realService.getClass().getInterfaces(); //直接实现目标的接口的情况下使用java原生动态代理,否则使用cglib if (find(inters, inter)) { this.proxyService = Proxy.newProxyInstance( realService.getClass().getClassLoader(), realService.getClass().getInterfaces(), this ); } else { Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(this.realService.getClass()); // 回调方法 enhancer.setCallback(this); // 创建代理对象 this.proxyService = enhancer.create(); } }
@Test public void testEventHandlerCallsRedirectToAdapter() { Object result1 = testSubject.postProcessBeforeInitialization(new AnnotatedEventListener(), "beanName"); Object postProcessedBean = testSubject.postProcessAfterInitialization(result1, "beanName"); assertTrue(Enhancer.isEnhanced(postProcessedBean.getClass())); assertTrue(postProcessedBean instanceof EventListener); assertTrue(postProcessedBean instanceof AnnotatedEventListener); EventListener eventListener = (EventListener) postProcessedBean; AnnotatedEventListener annotatedEventListener = (AnnotatedEventListener) postProcessedBean; eventListener.canHandle(StubDomainEvent.class); StubDomainEvent domainEvent = new StubDomainEvent(); eventListener.handle(domainEvent); verify(mockAdapter).canHandle(StubDomainEvent.class); verify(mockAdapter).handle(domainEvent); reset(mockAdapter); annotatedEventListener.handleEvent(new StubDomainEvent()); verifyZeroInteractions(mockAdapter); }
private Object createProxyReturnObject(final Method method) { if (method.getReturnType() == void.class) { return null; } /* The method is expected to return _something_, so we create a proxy for it */ final String eventName = localContext.generateEventName(new Event() { @Override public String name() { return method.getReturnType().getName(); } }); final ReturnGivenStringCallback eventNameCallback = new ReturnGivenStringCallback(eventName); final ReturnGivenStringCallback realClassNameCallback = new ReturnGivenStringCallback(method.getReturnType().getName()); final ProxyEventCallbackFilter filter = new ProxyEventCallbackFilter(method.getReturnType(),new Class[]{Intercepted.class}) { @Override protected ReturnGivenStringCallback getRealClassName() { return realClassNameCallback; } @Override public ReturnGivenStringCallback getNameCallback() { return eventNameCallback; } }; return Enhancer.create(method.getReturnType(), new Class[]{Intercepted.class}, filter, filter.getCallbacks()); }
public static void aopBase() { // 设计模式-代理模式(静态代理) System.out.println("设计模式-代理模式"); ISubject sub = new SubjectImpProxy(new SubjectImp()); sub.request(); // JDK-动态代理,通过Proxy生成代理类 System.out.println("\nJDK-动态代理"); // Proxy:提供用于创建动态代理类和实例的静态方法,它还是由这些方法创建的所有动态代理类的超类。 sub = (ISubject) Proxy.newProxyInstance( // 指定Classloader FXmain.class.getClassLoader(), // 指定要生成代理的接口,等同于 ISubject.class.getInterfaces() new Class[] { ISubject.class }, // 初始化动态代理类,实现InvocationHandler接口的实现类 new RequestInvocationHandler(new SubjectImp())); sub.request(); // cglib-动态字节码生成 System.out.println("\ncglib-动态字节码生成"); Enhancer hancer = new Enhancer(); hancer.setSuperclass(Requestable.class); hancer.setCallback(new RequestCallback()); Requestable req = (Requestable) hancer.create(); req.request(); }
@SuppressWarnings("unchecked") public T bind() { if (__bound == null) { __bound = (T) ClassUtils.wrapper(__source).duplicate(Enhancer.create(__targetClass, new MethodInterceptor() { public Object intercept(Object targetObject, Method targetMethod, Object[] methodParams, MethodProxy methodProxy) throws Throwable { Object _result = methodProxy.invokeSuper(targetObject, methodParams); PropertyStateMeta _meta = __propertyStates.get(targetMethod.getName()); if (_meta != null && ArrayUtils.isNotEmpty(methodParams) && !ObjectUtils.equals(_meta.getOriginalValue(), methodParams[0])) { _meta.setNewValue(methodParams[0]); } return _result; } })); } return __bound; }
@Override public Supplier<Object> scope(Supplier<Object> supplier, Binding binding, CoreDependencyKey<?> requestedKey) { // create the proxy right away, such that it can be reused // afterwards Object proxy = Enhancer.create(requestedKey.getRawType(), new Dispatcher() { @Override public Object loadObject() throws Exception { Map<Binding, Object> scopedObjects = tryGetValueMap().orElseThrow( () -> new RuntimeException("Cannot access " + requestedKey + " outside of scope " + scopeName)); return scopedObjects.computeIfAbsent(binding, b -> supplier.get()); } }); return () -> proxy; }
public BasicProxyFactoryImpl(Class superClass, Class[] interfaces) { if ( superClass == null && ( interfaces == null || interfaces.length < 1 ) ) { throw new AssertionFailure( "attempting to build proxy without any superclass or interfaces" ); } Enhancer en = new Enhancer(); en.setUseCache( false ); en.setInterceptDuringConstruction( false ); en.setUseFactory( true ); en.setCallbackTypes( CALLBACK_TYPES ); en.setCallbackFilter( FINALIZE_FILTER ); if ( superClass != null ) { en.setSuperclass( superClass ); } if ( interfaces != null && interfaces.length > 0 ) { en.setInterfaces( interfaces ); } proxyClass = en.createClass(); try { factory = ( Factory ) proxyClass.newInstance(); } catch ( Throwable t ) { throw new HibernateException( "Unable to build CGLIB Factory instance" ); } }
@Test public void assertThatLog4jMockPolicyWorks() throws Exception { final Log4jUser tested = createPartialMockAndInvokeDefaultConstructor(Log4jUser.class, "getMessage"); final String otherMessage = "other message"; final String firstMessage = "first message and "; expect(tested.getMessage()).andReturn(firstMessage); replayAll(); final String actual = tested.mergeMessageWith(otherMessage); Class<? extends Logger> class1 = Whitebox.getInternalState(Log4jUserParent.class, Logger.class).getClass(); assertTrue(Enhancer.isEnhanced(class1)); verifyAll(); assertEquals(firstMessage + otherMessage, actual); }
/** * @return A proxy object whose getters will return null for unchanged entity's properties * (and new values for changed properties), or the entity itself if the entity was not * enhanced for dirty checking. * @throws com.currencycloud.client.CurrencyCloudClient.NoChangeException if the entity was dirty-checked * but there were no changes. */ static <E extends Entity> E wrapIfDirty(E entity, Class<E> entityClass) throws NoChangeException { if (entity != null) { Map<String, Object> values = getDirtyProperties(entity); if (values != null) { if (values.isEmpty()) { throw new NoChangeException(); } values = new HashMap<>(values); values.put("id", entity.getId()); Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(entityClass); enhancer.setCallback(new ModifiedValueProvider(values)); return (E) enhancer.create(); } } return entity; }
@SuppressWarnings("unchecked") @Override public <T> T create(final Class<T> clazz) { checkNotNull(clazz, "clazz cannot be null"); if (!isAbstract(clazz)) { return null; } checkIfSupported(clazz); final Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(clazz); enhancer.setCallback(handler); return (T) enhancer.create(); }
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); }
public void testProxyTypeCanBeAliased() throws MalformedURLException { final Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(HashMap.class); enhancer.setCallback(new DelegatingHandler(new HashMap())); final Map orig = (Map)enhancer.create(); orig.put("URL", new URL("http://xstream.codehaus.org")); xstream.aliasType("cglib", Map.class); final String expected = "" + "<cglib>\n" + " <type>java.util.HashMap</type>\n" + " <interfaces/>\n" + " <hasFactory>true</hasFactory>\n" + " <com.thoughtworks.acceptance.CglibCompatibilityTest_-DelegatingHandler>\n" + " <delegate class=\"map\">\n" + " <entry>\n" + " <string>URL</string>\n" + " <url>http://xstream.codehaus.org</url>\n" + " </entry>\n" + " </delegate>\n" + " </com.thoughtworks.acceptance.CglibCompatibilityTest_-DelegatingHandler>\n" + "</cglib>"; assertEquals(expected, xstream.toXML(orig)); }
public T getProxy() { Class proxyClass = getProxy(delegateClass.getName()); if (proxyClass == null) { Enhancer enhancer = new Enhancer(); if (delegateClass.isInterface()) { // 判断是否为接口,优先进行接口代理可以解决service为final enhancer.setInterfaces(new Class[] { delegateClass }); } else { enhancer.setSuperclass(delegateClass); } enhancer.setCallbackTypes(new Class[] { ProxyDirect.class, ProxyInterceptor.class }); enhancer.setCallbackFilter(new ProxyRoute()); proxyClass = enhancer.createClass(); // 注册proxyClass registerProxy(delegateClass.getName(), proxyClass); } Enhancer.registerCallbacks(proxyClass, new Callback[] { new ProxyDirect(), new ProxyInterceptor() }); try { Object[] _constructorArgs = new Object[0]; Constructor _constructor = proxyClass.getConstructor(new Class[] {});// 先尝试默认的空构造函数 return (T) _constructor.newInstance(_constructorArgs); } catch (Throwable e) { throw new OptimizerException(e); } finally { // clear thread callbacks to allow them to be gc'd Enhancer.registerStaticCallbacks(proxyClass, null); } }
@SuppressWarnings("unchecked") public <T> T create(Class<T> clazz, String widgetId) { // creating proxy class Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(clazz); enhancer.setUseFactory(true); enhancer.setCallbackType(RemoteObjectMethodInterceptor.class); if (clazz.getSigners() != null) { enhancer.setNamingPolicy(NAMING_POLICY_FOR_CLASSES_IN_SIGNED_PACKAGES); } Class<?> proxyClass = enhancer.createClass(); // instantiating class without constructor call ObjenesisStd objenesis = new ObjenesisStd(); Factory proxy = (Factory) objenesis.newInstance(proxyClass); proxy.setCallbacks(new Callback[]{new RemoteObjectMethodInterceptor(this, invoker, widgetId)}); T widget = (T) proxy; widgetIds.put(widget, widgetId); return widget; }
/** * Create an adapter for the given {@code object} in a specific {@code type}. * * @param adaptableObject the object to adapt * @param adapterType the class in which the object must be adapted * * @return an adapted object in the given {@code type} */ private static Object createAdapter(Object adaptableObject, Class<?> adapterType) { /* * Compute the interfaces that the proxy has to implement * These are the current interfaces + PersistentEObject */ List<Class<?>> interfaces = ClassUtils.getAllInterfaces(adaptableObject.getClass()); interfaces.add(PersistentEObject.class); // Create the proxy Enhancer proxy = new Enhancer(); /* * Use the ClassLoader of the type, otherwise it will cause OSGi troubles (like project trying to * create an PersistentEObject while it does not have a dependency to NeoEMF core) */ proxy.setClassLoader(adapterType.getClassLoader()); proxy.setSuperclass(adaptableObject.getClass()); proxy.setInterfaces(interfaces.toArray(new Class[interfaces.size()])); proxy.setCallback(new PersistentEObjectProxyHandler()); return proxy.create(); }