net.sf.cglib.proxy.Enhancer Java Examples

The following examples show how to use net.sf.cglib.proxy.Enhancer. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ClassLoaderAdapterProxiedTest.java    From furnace with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void testCanAdaptFinalResultReturnTypeObject() throws Exception
{
   ClassLoader loader = MockService.class.getClassLoader();
   final MockService internal = new MockService();

   MockService delegate = (MockService) Enhancer.create(MockService.class, new LazyLoader()
   {
      @Override
      public Object loadObject() throws Exception
      {
         return internal;
      }
   });

   MockService adapter = ClassLoaderAdapterBuilder.callingLoader(loader).delegateLoader(loader)
            .enhance(delegate, MockService.class);

   Assert.assertNotEquals(internal.getResultFinalReturnTypeObject(), adapter.getResultFinalReturnTypeObject());
   Assert.assertEquals(((Result) internal.getResultFinalReturnTypeObject()).getValue(),
            ((Result) adapter.getResultFinalReturnTypeObject()).getValue());
}
 
Example #2
Source File: ClassLoaderAdapterProxiedTest.java    From furnace with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void testAdaptFinalResult() throws Exception
{
   ClassLoader loader = MockService.class.getClassLoader();
   final MockService internal = new MockService();

   MockService delegate = (MockService) Enhancer.create(MockService.class, new LazyLoader()
   {
      @Override
      public Object loadObject() throws Exception
      {
         return internal;
      }
   });

   MockService adapter = ClassLoaderAdapterBuilder.callingLoader(loader).delegateLoader(loader)
            .enhance(delegate, MockService.class);

   Assert.assertNotEquals(internal.getResultInterfaceFinalImpl(), adapter.getResultInterfaceFinalImpl());
   Object unwrapped = Proxies.unwrap(adapter);
   Assert.assertNotSame(adapter, unwrapped);
}
 
Example #3
Source File: CglibProxy.java    From festival with Apache License 2.0 6 votes vote down vote up
@Override
public Object getProxy(ClassLoader classLoader) {
    Enhancer enhancer = new Enhancer();
    enhancer.setClassLoader(classLoader);
    enhancer.setCallbackType(MethodInterceptor.class);

    Class<?> targetClass = support.getBeanClass();
    enhancer.setSuperclass(targetClass);
    enhancer.setInterfaces(new Class[]{FestivalProxy.class, TargetClassAware.class});
    Class<?> proxyClass = enhancer.createClass();

    Objenesis objenesis = new ObjenesisStd();
    ObjectInstantiator<?> instantiator = objenesis.getInstantiatorOf(proxyClass);
    Object proxyInstance = instantiator.newInstance();

    ((Factory) proxyInstance).setCallbacks(new Callback[]{new CglibMethodInterceptor(support)});

    return proxyInstance;
}
 
Example #4
Source File: ReflectiveParserManifest.java    From ProjectAres with GNU Affero General Public License v3.0 6 votes vote down vote up
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);
}
 
Example #5
Source File: ClassByImplementationBenchmark.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
/**
 * 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}) {
        protected Object getCallback(Method method) {
            if (method.getDeclaringClass() == baseClass) {
                return new FixedValue() {
                    public Object loadObject() {
                        return null;
                    }
                };
            } else {
                return NoOp.INSTANCE;
            }
        }
    };
    enhancer.setCallbackFilter(callbackHelper);
    enhancer.setCallbacks(callbackHelper.getCallbacks());
    return (ExampleInterface) enhancer.create();
}
 
Example #6
Source File: CglibProxy.java    From rpcx-java with Apache License 2.0 6 votes vote down vote up
public <T> T getProxy(Class<?> clazz, final BiFunction<Method, Object[], Object> function) {
    Enhancer e = new Enhancer();
    e.setSuperclass(clazz);
    e.setCallback((net.sf.cglib.proxy.InvocationHandler) (proxy, method, args) -> {
        String methodName = method.getName();
        if ("getClass".equals(methodName)) {
            return proxy.getClass();
        }
        if ("hashCode".equals(methodName)) {
            return proxy.hashCode();
        }
        if ("toString".equals(methodName)) {
            return proxy.toString();
        }
        return function.apply(method, args);
    });
    return (T) e.create();
}
 
Example #7
Source File: ClassLoaderAdapterProxiedTest.java    From furnace with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void testAdaptProxiedResultReturnTypeObject() throws Exception
{
   ClassLoader loader = MockService.class.getClassLoader();
   final MockService internal = new MockService();

   MockService delegate = (MockService) Enhancer.create(MockService.class, new LazyLoader()
   {
      @Override
      public Object loadObject() throws Exception
      {
         return internal;
      }
   });

   MockService adapter = ClassLoaderAdapterBuilder.callingLoader(loader).delegateLoader(loader)
            .enhance(delegate, MockService.class);

   Assert.assertNotEquals(internal.getResult(), adapter.getResultEnhancedReturnTypeObject());
}
 
Example #8
Source File: ClassLoaderAdapterProxiedTest.java    From furnace with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void testAdaptProxiedResult() throws Exception
{
   ClassLoader loader = MockService.class.getClassLoader();
   final MockService internal = new MockService();

   MockService delegate = (MockService) Enhancer.create(MockService.class, new LazyLoader()
   {
      @Override
      public Object loadObject() throws Exception
      {
         return internal;
      }
   });

   MockService adapter = ClassLoaderAdapterBuilder.callingLoader(loader).delegateLoader(loader)
            .enhance(delegate, MockService.class);

   Assert.assertNotEquals(internal.getResult(), adapter.getResultEnhanced());
}
 
Example #9
Source File: ComponentInstantiationPostProcessor.java    From cloudstack with Apache License 2.0 6 votes vote down vote up
@Override
public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
    if (_interceptors != null && _interceptors.size() > 0) {
        if (ComponentMethodInterceptable.class.isAssignableFrom(beanClass)) {
            Enhancer enhancer = new Enhancer();
            enhancer.setSuperclass(beanClass);
            enhancer.setCallbacks(getCallbacks());
            enhancer.setCallbackFilter(getCallbackFilter());
            enhancer.setNamingPolicy(ComponentNamingPolicy.INSTANCE);

            Object bean = enhancer.create();
            return bean;
        }
    }
    return null;
}
 
Example #10
Source File: ProxyFactory.java    From businessworks with Apache License 2.0 6 votes vote down vote up
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();
  }
}
 
Example #11
Source File: NotesNativeAPI.java    From domino-jna with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
	}
}
 
Example #12
Source File: ComponentInstantiationPostProcessor.java    From cosmic with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #13
Source File: TaskInterceptor.java    From flux with Apache License 2.0 6 votes vote down vote up
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());
}
 
Example #14
Source File: PropertyStateSupport.java    From ymate-platform-v2 with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public T bind() {
    if (__bound == null) {
        __bound = (T) ClassUtils.wrapper(__source).duplicate(Enhancer.create(__targetClass, new MethodInterceptor() {
            @Override
            public Object intercept(Object targetObject, Method targetMethod, Object[] methodParams, MethodProxy methodProxy) throws Throwable {
                PropertyStateMeta _meta = __propertyStates.get(targetMethod.getName());
                if (_meta != null && ArrayUtils.isNotEmpty(methodParams) && !ObjectUtils.equals(_meta.getOriginalValue(), methodParams[0])) {
                    if (__ignoreNull && methodParams[0] == null) {
                        methodParams[0] = _meta.getOriginalValue();
                    }
                    _meta.setNewValue(methodParams[0]);
                }
                return methodProxy.invokeSuper(targetObject, methodParams);
            }
        }));
    }
    return __bound;
}
 
Example #15
Source File: ProxyFactoryFactoryImpl.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
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" );
	}
}
 
Example #16
Source File: ClassLoaderAdapterProxiedTest.java    From furnace with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void testShouldNotProxyJavaUtilLogging() throws Exception {
   ClassLoader loader = JavaUtilLoggingFactory.class.getClassLoader();
   final JavaUtilLoggingFactory internal = new JavaUtilLoggingFactory();

   JavaUtilLoggingFactory delegate = (JavaUtilLoggingFactory) Enhancer.create(JavaUtilLoggingFactory.class, new LazyLoader() {
      @Override
      public Object loadObject() throws Exception {
         return internal;
      }
   });

   JavaUtilLoggingFactory adapter = ClassLoaderAdapterBuilder.callingLoader(loader).delegateLoader(loader)
           .enhance(delegate, JavaUtilLoggingFactory.class);
   LogRecord logRecord = adapter.getLogRecord();
   Assert.assertFalse(Proxies.isProxyType(logRecord.getClass()));
   Assert.assertFalse(Proxies.isProxyType(logRecord.getLevel().getClass()));
}
 
Example #17
Source File: ClassLoaderAdapterProxiedTest.java    From furnace with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void testNullValuesAsMethodParameters() throws Exception
{
   ClassLoader loader = MockService.class.getClassLoader();
   final MockService internal = new MockService();

   MockService delegate = (MockService) Enhancer.create(MockService.class, new LazyLoader()
   {
      @Override
      public Object loadObject() throws Exception
      {
         return internal;
      }
   });
   MockService adapter = ClassLoaderAdapterBuilder.callingLoader(loader).delegateLoader(loader)
            .enhance(delegate, MockService.class);
   Assert.assertNull(internal.echo(null));
   Assert.assertNull(adapter.echo(null));
}
 
Example #18
Source File: ProxyFactory.java    From businessworks with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked") // the constructor promises to produce 'T's
public T newInstance(Object... arguments) throws InvocationTargetException {
  Enhancer.registerCallbacks(enhanced, callbacks);
  try {
    return (T) fastClass.newInstance(constructorIndex, arguments);
  } finally {
    Enhancer.registerCallbacks(enhanced, null);
  }
}
 
Example #19
Source File: MethodAreaOOM.java    From JavaBase with MIT License 5 votes vote down vote up
public static void main(String[] args) {
  while (true) {
    Enhancer enhancer = new Enhancer();
    enhancer.setSuperclass(OOMObject.class);
    enhancer.setUseCache(false);
    enhancer.setCallback((MethodInterceptor) (obj, method, args1, proxy) ->
        proxy.invokeSuper(obj, args)
    );
    enhancer.create();
  }
}
 
Example #20
Source File: DefaultMQProducerCglibProxyFactory.java    From pepper-metrics with Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public <T> T getProxy(Class<T> clz, String namespace, Class[] argumentTypes, Object[] arguments) {
    Enhancer enhancer = new Enhancer();
    enhancer.setSuperclass(clz);
    enhancer.setCallback(new DefaultMQProducerMethodInterceptor(namespace));
    return (T) enhancer.create(argumentTypes, arguments);
}
 
Example #21
Source File: CGLIBMapper.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public String serializedClass(Class type) {
    String serializedName = super.serializedClass(type);
    if (type == null) {
        return serializedName;
    }
    String typeName = type.getName();
    return typeName.equals(serializedName)
        && typeName.indexOf(DEFAULT_NAMING_MARKER) > 0
        && Enhancer.isEnhanced(type) ? alias : serializedName;
}
 
Example #22
Source File: RpcCallbackDispatcher.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public T getTarget() {
    return (T)Enhancer.create(_targetObject.getClass(), new MethodInterceptor() {
        @Override
        public Object intercept(Object arg0, Method arg1, Object[] arg2, MethodProxy arg3) throws Throwable {
            _callbackMethod = arg1;
            return null;
        }
    });
}
 
Example #23
Source File: ProxyFactory.java    From businessworks with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked") // the constructor promises to construct 'T's
ProxyConstructor(Enhancer enhancer, InjectionPoint injectionPoint, Callback[] callbacks,
    ImmutableMap<Method, List<MethodInterceptor>> methodInterceptors) {
  this.enhanced = enhancer.createClass(); // this returns a cached class if possible
  this.injectionPoint = injectionPoint;
  this.constructor = (Constructor<T>) injectionPoint.getMember();
  this.callbacks = callbacks;
  this.methodInterceptors = methodInterceptors;
  this.fastClass = newFastClassForMember(enhanced, constructor);
  this.constructorIndex = fastClass.getIndex(constructor.getParameterTypes());
}
 
Example #24
Source File: ClassUtilsTest.java    From reflection-util with Apache License 2.0 5 votes vote down vote up
private static <T> T createCglibProxy(T object) {
	Enhancer enhancer = new Enhancer();
	enhancer.setSuperclass(object.getClass());
	enhancer.setCallback((FixedValue) () -> null);
	@SuppressWarnings("unchecked")
	T proxy = (T) enhancer.create();
	return proxy;
}
 
Example #25
Source File: Client.java    From code with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
    Enhancer enhancer = new Enhancer();
    enhancer.setSuperclass(RealSubject.class);
    enhancer.setCallback(new DemoMethodInterceptor());
    Subject subject = (Subject) enhancer.create();
    subject.request();
}
 
Example #26
Source File: Cglib2AopProxy.java    From tiny-spring with Apache License 2.0 5 votes vote down vote up
@Override
public Object getProxy() {
	Enhancer enhancer = new Enhancer();
	enhancer.setSuperclass(advised.getTargetSource().getTargetClass());
	enhancer.setInterfaces(advised.getTargetSource().getInterfaces());
	/** Enhancer.java中setCallback方法源码
	 *	public void setCallback(final Callback callback) {
	 *       setCallbacks(new Callback[]{ callback });
	 *  }
    */
    // 设置回调方法
	enhancer.setCallback(new DynamicAdvisedInterceptor(advised));
	Object enhanced = enhancer.create();
	return enhanced;
}
 
Example #27
Source File: RefreshableProxy.java    From config-toolkit with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public RefreshableProxy(final T target) {
	super();
	this.target = target;
	final Enhancer enhancer = new Enhancer();
	enhancer.setSuperclass(this.target.getClass());
	enhancer.setCallback(this);
	proxy = (T) enhancer.create();
}
 
Example #28
Source File: Cglib2AopProxy.java    From tiny-spring with Apache License 2.0 5 votes vote down vote up
@Override
public Object getProxy() {
	Enhancer enhancer = new Enhancer();
	enhancer.setSuperclass(advised.getTargetSource().getTargetClass());
	enhancer.setInterfaces(advised.getTargetSource().getInterfaces());
	//设置代理类的通知方法,相当于设置拦截器方法
	enhancer.setCallback(new DynamicAdvisedInterceptor(advised));
	Object enhanced = enhancer.create();
	return enhanced;
}
 
Example #29
Source File: Lesson4_2.java    From java-interview with Apache License 2.0 5 votes vote down vote up
public Object getInstance(Object target) {
    this.target = target;
    Enhancer enhancer = new Enhancer();
    // 设置父类为实例类
    enhancer.setSuperclass(this.target.getClass());
    // 回调方法
    enhancer.setCallback(this);
    // 创建代理对象
    return enhancer.create();
}
 
Example #30
Source File: MockService.java    From furnace with Eclipse Public License 1.0 5 votes vote down vote up
public MockResult getResultEnhanced()
{
   final MockResult internal = new MockResult();
   MockResult delegate = (MockResult) Enhancer.create(MockResult.class, new LazyLoader()
   {
      @Override
      public Object loadObject() throws Exception
      {
         return internal;
      }
   });

   return delegate;
}