org.springframework.cglib.proxy.Callback Java Examples

The following examples show how to use org.springframework.cglib.proxy.Callback. 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: CglibSubclassingInstantiationStrategy.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Create a new instance of a dynamically generated subclass implementing the
 * required lookups.
 * @param ctor constructor to use. If this is {@code null}, use the
 * no-arg constructor (no parameterization, or Setter Injection)
 * @param args arguments to use for the constructor.
 * Ignored if the {@code ctor} parameter is {@code null}.
 * @return new instance of the dynamically generated subclass
 */
public Object instantiate(Constructor<?> ctor, Object... args) {
	Class<?> subclass = createEnhancedSubclass(this.beanDefinition);
	Object instance;
	if (ctor == null) {
		instance = BeanUtils.instantiateClass(subclass);
	}
	else {
		try {
			Constructor<?> enhancedSubclassConstructor = subclass.getConstructor(ctor.getParameterTypes());
			instance = enhancedSubclassConstructor.newInstance(args);
		}
		catch (Exception ex) {
			throw new BeanInstantiationException(this.beanDefinition.getBeanClass(),
					"Failed to invoke constructor for CGLIB enhanced subclass [" + subclass.getName() + "]", ex);
		}
	}
	// SPR-10785: set callbacks directly on the instance instead of in the
	// enhanced class (via the Enhancer) in order to avoid memory leaks.
	Factory factory = (Factory) instance;
	factory.setCallbacks(new Callback[] {NoOp.INSTANCE,
			new LookupOverrideMethodInterceptor(this.beanDefinition, this.owner),
			new ReplaceOverrideMethodInterceptor(this.beanDefinition, this.owner)});
	return instance;
}
 
Example #2
Source File: CglibAopProxy.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) {
	Object other = args[0];
	if (proxy == other) {
		return true;
	}
	if (other instanceof Factory) {
		Callback callback = ((Factory) other).getCallback(INVOKE_EQUALS);
		if (!(callback instanceof EqualsInterceptor)) {
			return false;
		}
		AdvisedSupport otherAdvised = ((EqualsInterceptor) callback).advised;
		return AopProxyUtils.equalsInProxy(this.advised, otherAdvised);
	}
	else {
		return false;
	}
}
 
Example #3
Source File: CglibSubclassingInstantiationStrategy.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * Create a new instance of a dynamically generated subclass implementing the
 * required lookups.
 * @param ctor constructor to use. If this is {@code null}, use the
 * no-arg constructor (no parameterization, or Setter Injection)
 * @param args arguments to use for the constructor.
 * Ignored if the {@code ctor} parameter is {@code null}.
 * @return new instance of the dynamically generated subclass
 */
public Object instantiate(Constructor<?> ctor, Object... args) {
	Class<?> subclass = createEnhancedSubclass(this.beanDefinition);
	Object instance;
	if (ctor == null) {
		instance = BeanUtils.instantiate(subclass);
	}
	else {
		try {
			Constructor<?> enhancedSubclassConstructor = subclass.getConstructor(ctor.getParameterTypes());
			instance = enhancedSubclassConstructor.newInstance(args);
		}
		catch (Exception ex) {
			throw new BeanInstantiationException(this.beanDefinition.getBeanClass(),
					"Failed to invoke constructor for CGLIB enhanced subclass [" + subclass.getName() + "]", ex);
		}
	}
	// SPR-10785: set callbacks directly on the instance instead of in the
	// enhanced class (via the Enhancer) in order to avoid memory leaks.
	Factory factory = (Factory) instance;
	factory.setCallbacks(new Callback[] {NoOp.INSTANCE,
			new LookupOverrideMethodInterceptor(this.beanDefinition, this.owner),
			new ReplaceOverrideMethodInterceptor(this.beanDefinition, this.owner)});
	return instance;
}
 
Example #4
Source File: AbstractResolver.java    From spring-data with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings({ "rawtypes", "unchecked" })
protected Object proxy(
	final String id,
	final TypeInformation<?> type,
	final A annotation,
	final ResolverCallback<A> callback) {
	final ProxyInterceptor interceptor = new ProxyInterceptor(id, type, annotation, callback, conversionService);
	if (type.getType().isInterface()) {
		final ProxyFactory proxyFactory = new ProxyFactory(new Class<?>[] { type.getType() });
		for (final Class<?> interf : type.getType().getInterfaces()) {
			proxyFactory.addInterface(interf);
		}
		proxyFactory.addInterface(LazyLoadingProxy.class);
		proxyFactory.addAdvice(interceptor);
		return proxyFactory.getProxy();
	} else {
		final Factory factory = (Factory) objenesis.newInstance(enhancedTypeFor(type.getType()));
		factory.setCallbacks(new Callback[] { interceptor });
		return factory;
	}
}
 
Example #5
Source File: CglibSubclassingInstantiationStrategy.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Create a new instance of a dynamically generated subclass implementing the
 * required lookups.
 * @param ctor constructor to use. If this is {@code null}, use the
 * no-arg constructor (no parameterization, or Setter Injection)
 * @param args arguments to use for the constructor.
 * Ignored if the {@code ctor} parameter is {@code null}.
 * @return new instance of the dynamically generated subclass
 */
public Object instantiate(@Nullable Constructor<?> ctor, Object... args) {
	Class<?> subclass = createEnhancedSubclass(this.beanDefinition);
	Object instance;
	if (ctor == null) {
		instance = BeanUtils.instantiateClass(subclass);
	}
	else {
		try {
			Constructor<?> enhancedSubclassConstructor = subclass.getConstructor(ctor.getParameterTypes());
			instance = enhancedSubclassConstructor.newInstance(args);
		}
		catch (Exception ex) {
			throw new BeanInstantiationException(this.beanDefinition.getBeanClass(),
					"Failed to invoke constructor for CGLIB enhanced subclass [" + subclass.getName() + "]", ex);
		}
	}
	// SPR-10785: set callbacks directly on the instance instead of in the
	// enhanced class (via the Enhancer) in order to avoid memory leaks.
	Factory factory = (Factory) instance;
	factory.setCallbacks(new Callback[] {NoOp.INSTANCE,
			new LookupOverrideMethodInterceptor(this.beanDefinition, this.owner),
			new ReplaceOverrideMethodInterceptor(this.beanDefinition, this.owner)});
	return instance;
}
 
Example #6
Source File: CglibAopProxy.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Override
public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) {
	Object other = args[0];
	if (proxy == other) {
		return true;
	}
	if (other instanceof Factory) {
		Callback callback = ((Factory) other).getCallback(INVOKE_EQUALS);
		if (!(callback instanceof EqualsInterceptor)) {
			return false;
		}
		AdvisedSupport otherAdvised = ((EqualsInterceptor) callback).advised;
		return AopProxyUtils.equalsInProxy(this.advised, otherAdvised);
	}
	else {
		return false;
	}
}
 
Example #7
Source File: CglibDynamicConfigurationInstanceCreator.java    From conf4j with MIT License 6 votes vote down vote up
@Override
public <T> T createInstance(ConfigurationModel configurationModel, ClassLoader classLoader) {
    Class<?> configurationType = configurationModel.getConfigurationType();

    Enhancer enhancer = new Enhancer();
    enhancer.setClassLoader(classLoader);
    enhancer.setNamingPolicy(Conf4jNamingPolicy.INSTANCE);
    enhancer.setInterceptDuringConstruction(false);
    if (configurationType.isInterface()) {
        enhancer.setInterfaces(new Class<?>[]{configurationType, DynamicConfiguration.class});
    } else {
        enhancer.setSuperclass(configurationType);
        enhancer.setInterfaces(new Class<?>[]{DynamicConfiguration.class});
    }
    enhancer.setCallbackFilter(new ProxyCallbackFilter(configurationModel));
    enhancer.setCallbacks(new Callback[]{
            new CglibDynamicConfigurationMethodInterceptor(configurationModel),
            new SerializableNoOp()
    });

    @SuppressWarnings("unchecked")
    T instance = (T) enhancer.create();
    return instance;
}
 
Example #8
Source File: CglibAopProxy.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) {
	Object other = args[0];
	if (proxy == other) {
		return true;
	}
	if (other instanceof Factory) {
		Callback callback = ((Factory) other).getCallback(INVOKE_EQUALS);
		if (!(callback instanceof EqualsInterceptor)) {
			return false;
		}
		AdvisedSupport otherAdvised = ((EqualsInterceptor) callback).advised;
		return AopProxyUtils.equalsInProxy(this.advised, otherAdvised);
	}
	else {
		return false;
	}
}
 
Example #9
Source File: CglibStaticConfigurationInstanceCreator.java    From conf4j with MIT License 6 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public <T> T createInstance(ConfigurationModel configurationModel, ClassLoader classLoader) {
    Class<?> configurationType = configurationModel.getConfigurationType();

    Enhancer enhancer = new Enhancer();
    enhancer.setClassLoader(classLoader);
    enhancer.setNamingPolicy(Conf4jNamingPolicy.INSTANCE);
    enhancer.setInterceptDuringConstruction(false);
    if (configurationType.isInterface()) {
        enhancer.setInterfaces(new Class<?>[]{configurationType, Serializable.class});
    } else {
        enhancer.setSuperclass(configurationType);
        enhancer.setInterfaces(new Class<?>[]{Serializable.class});
    }
    enhancer.setCallbackFilter(new ProxyCallbackFilter(configurationModel));
    enhancer.setCallbacks(new Callback[]{
            new CglibStaticConfigurationMethodInterceptor(configurationModel),
            new SerializableNoOp(),
    });

    return (T) enhancer.create();
}
 
Example #10
Source File: EagleTraceCglibProxy.java    From eagle with Apache License 2.0 6 votes vote down vote up
@Override
public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) {
    Object other = args[0];
    if (proxy == other) {
        return true;
    }
    if (other instanceof Factory) {
        Callback callback = ((Factory) other).getCallback(INVOKE_EQUALS);
        if (!(callback instanceof EagleTraceCglibProxy.EqualsInterceptor)) {
            return false;
        }
        AdvisedSupport otherAdvised = ((EagleTraceCglibProxy.EqualsInterceptor) callback).advised;
        return AopProxyUtils.equalsInProxy(this.advised, otherAdvised);
    } else {
        return false;
    }
}
 
Example #11
Source File: CglibSubclassingInstantiationStrategy.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Create a new instance of a dynamically generated subclass implementing the
 * required lookups.
 * @param ctor constructor to use. If this is {@code null}, use the
 * no-arg constructor (no parameterization, or Setter Injection)
 * @param args arguments to use for the constructor.
 * Ignored if the {@code ctor} parameter is {@code null}.
 * @return new instance of the dynamically generated subclass
 */
public Object instantiate(@Nullable Constructor<?> ctor, Object... args) {
	Class<?> subclass = createEnhancedSubclass(this.beanDefinition);
	Object instance;
	if (ctor == null) {
		instance = BeanUtils.instantiateClass(subclass);
	}
	else {
		try {
			Constructor<?> enhancedSubclassConstructor = subclass.getConstructor(ctor.getParameterTypes());
			instance = enhancedSubclassConstructor.newInstance(args);
		}
		catch (Exception ex) {
			throw new BeanInstantiationException(this.beanDefinition.getBeanClass(),
					"Failed to invoke constructor for CGLIB enhanced subclass [" + subclass.getName() + "]", ex);
		}
	}
	// SPR-10785: set callbacks directly on the instance instead of in the
	// enhanced class (via the Enhancer) in order to avoid memory leaks.
	Factory factory = (Factory) instance;
	factory.setCallbacks(new Callback[] {NoOp.INSTANCE,
			new LookupOverrideMethodInterceptor(this.beanDefinition, this.owner),
			new ReplaceOverrideMethodInterceptor(this.beanDefinition, this.owner)});
	return instance;
}
 
Example #12
Source File: CglibAopProxy.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) {
	Object other = args[0];
	if (proxy == other) {
		return true;
	}
	if (other instanceof Factory) {
		Callback callback = ((Factory) other).getCallback(INVOKE_EQUALS);
		if (!(callback instanceof EqualsInterceptor)) {
			return false;
		}
		AdvisedSupport otherAdvised = ((EqualsInterceptor) callback).advised;
		return AopProxyUtils.equalsInProxy(this.advised, otherAdvised);
	}
	else {
		return false;
	}
}
 
Example #13
Source File: EagleTraceCglibProxy.java    From eagle with Apache License 2.0 6 votes vote down vote up
private Callback[] getCallbacks() throws Exception {

        // Choose an "aop" interceptor (used for AOP calls).
        Callback aopInterceptor = new EagleTraceCglibProxy.DynamicAdvisedInterceptor(this.advised);

        // Choose a "straight to target" interceptor. (used for calls that are
        // unadvised but can return this). May be required to expose the proxy.
        Callback targetInterceptor = new EagleTraceCglibProxy.DynamicUnadvisedInterceptor(this.advised.getTargetSource());


        // Choose a "direct to target" dispatcher (used for
        // unadvised calls to static targets that cannot return this).
        Callback targetDispatcher = new EagleTraceCglibProxy.SerializableNoOp();

        Callback[] callbacks = new Callback[]{
                aopInterceptor, // for normal advice
                targetInterceptor, // invoke target without considering advice, if optimized
                new EagleTraceCglibProxy.SerializableNoOp(), // no override for methods mapped to this
                targetDispatcher, this.advisedDispatcher,
                new EagleTraceCglibProxy.EqualsInterceptor(this.advised),
                new EagleTraceCglibProxy.HashCodeInterceptor(this.advised)
        };


        return callbacks;
    }
 
Example #14
Source File: LazyUtil.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
private static SimpleLazyDynamicInvocationHandler getProxy(Object object) {
	if (Proxy.isProxyClass(object.getClass())
			&& (Proxy.getInvocationHandler(object) instanceof SimpleLazyDynamicInvocationHandler)) {
		return (SimpleLazyDynamicInvocationHandler) Proxy
				.getInvocationHandler(object);
	}
	else if (object instanceof Factory) {
		Callback[] callbacks = ((Factory) object).getCallbacks();
		if (callbacks != null && callbacks.length == 1
				&& callbacks[0] instanceof SimpleLazyDynamicInvocationHandler) {
			return (SimpleLazyDynamicInvocationHandler) callbacks[0];
		}
	}
	return null;
}
 
Example #15
Source File: CglibAopProxy.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
protected Object createProxyClassAndInstance(Enhancer enhancer, Callback[] callbacks) {
	enhancer.setInterceptDuringConstruction(false);
	enhancer.setCallbacks(callbacks);
	return (this.constructorArgs != null ?
			enhancer.create(this.constructorArgTypes, this.constructorArgs) :
			enhancer.create());
}
 
Example #16
Source File: AddEnhancerMethodProxyTest.java    From HotswapAgent with GNU General Public License v2.0 5 votes vote down vote up
private A createEnhancer(Callback cb) {
    Enhancer enhancer = new Enhancer();
    enhancer.setSuperclass(AImpl.class);

    enhancer.setCallback(cb);
    final A a = (A) enhancer.create();
    return a;
}
 
Example #17
Source File: CglibSubclassingInstantiationStrategy.java    From blog_demos with Apache License 2.0 5 votes vote down vote up
/**
 * Create a new instance of a dynamically generated subclass implementing the
 * required lookups.
 * @param ctor constructor to use. If this is {@code null}, use the
 * no-arg constructor (no parameterization, or Setter Injection)
 * @param args arguments to use for the constructor.
 * Ignored if the {@code ctor} parameter is {@code null}.
 * @return new instance of the dynamically generated subclass
 */
Object instantiate(Constructor<?> ctor, Object[] args) {
	Class<?> subclass = createEnhancedSubclass(this.beanDefinition);

	Object instance;
	if (ctor == null) {
		instance = BeanUtils.instantiate(subclass);
	}
	else {
		try {
			Constructor<?> enhancedSubclassConstructor = subclass.getConstructor(ctor.getParameterTypes());
			instance = enhancedSubclassConstructor.newInstance(args);
		}
		catch (Exception e) {
			throw new BeanInstantiationException(this.beanDefinition.getBeanClass(), String.format(
				"Failed to invoke construcor for CGLIB enhanced subclass [%s]", subclass.getName()), e);
		}
	}

	// SPR-10785: set callbacks directly on the instance instead of in the
	// enhanced class (via the Enhancer) in order to avoid memory leaks.
	Factory factory = (Factory) instance;
	factory.setCallbacks(new Callback[] { NoOp.INSTANCE,//
		new LookupOverrideMethodInterceptor(beanDefinition, owner),//
		new ReplaceOverrideMethodInterceptor(beanDefinition, owner) });

	return instance;
}
 
Example #18
Source File: CglibAopProxy.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
protected Object createProxyClassAndInstance(Enhancer enhancer, Callback[] callbacks) {
	enhancer.setInterceptDuringConstruction(false);
	enhancer.setCallbacks(callbacks);
	return (this.constructorArgs != null ?
			enhancer.create(this.constructorArgTypes, this.constructorArgs) :
			enhancer.create());
}
 
Example #19
Source File: ConfigurationClassEnhancer.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
public ConditionalCallbackFilter(Callback[] callbacks) {
	this.callbacks = callbacks;
	this.callbackTypes = new Class<?>[callbacks.length];
	for (int i = 0; i < callbacks.length; i++) {
		this.callbackTypes[i] = callbacks[i].getClass();
	}
}
 
Example #20
Source File: CglibAopProxy.java    From spring-analysis-note with MIT License 5 votes vote down vote up
protected Object createProxyClassAndInstance(Enhancer enhancer, Callback[] callbacks) {
	enhancer.setInterceptDuringConstruction(false);
	enhancer.setCallbacks(callbacks);
	return (this.constructorArgs != null && this.constructorArgTypes != null ?
			enhancer.create(this.constructorArgTypes, this.constructorArgs) :
			enhancer.create());
}
 
Example #21
Source File: ConfigurationClassEnhancer.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public ConditionalCallbackFilter(Callback[] callbacks) {
	this.callbacks = callbacks;
	this.callbackTypes = new Class<?>[callbacks.length];
	for (int i = 0; i < callbacks.length; i++) {
		this.callbackTypes[i] = callbacks[i].getClass();
	}
}
 
Example #22
Source File: EagleTraceCglibProxy.java    From eagle with Apache License 2.0 5 votes vote down vote up
protected Object createProxyClassAndInstance(Enhancer enhancer, Callback[] callbacks) {
    enhancer.setInterceptDuringConstruction(false);
    enhancer.setCallbacks(callbacks);
    return (this.constructorArgs != null ?
            enhancer.create(this.constructorArgTypes, this.constructorArgs) :
            enhancer.create());
}
 
Example #23
Source File: ConfigurationClassEnhancer.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public int accept(Method method) {
	for (int i = 0; i < this.callbacks.length; i++) {
		Callback callback = this.callbacks[i];
		if (!(callback instanceof ConditionalCallback) || ((ConditionalCallback) callback).isMatch(method)) {
			return i;
		}
	}
	throw new IllegalStateException("No callback available for method " + method.getName());
}
 
Example #24
Source File: ConfigurationClassEnhancer.java    From java-technology-stack with MIT License 5 votes vote down vote up
public ConditionalCallbackFilter(Callback[] callbacks) {
	this.callbacks = callbacks;
	this.callbackTypes = new Class<?>[callbacks.length];
	for (int i = 0; i < callbacks.length; i++) {
		this.callbackTypes[i] = callbacks[i].getClass();
	}
}
 
Example #25
Source File: CglibAopProxy.java    From java-technology-stack with MIT License 5 votes vote down vote up
protected Object createProxyClassAndInstance(Enhancer enhancer, Callback[] callbacks) {
	enhancer.setInterceptDuringConstruction(false);
	enhancer.setCallbacks(callbacks);
	return (this.constructorArgs != null && this.constructorArgTypes != null ?
			enhancer.create(this.constructorArgTypes, this.constructorArgs) :
			enhancer.create());
}
 
Example #26
Source File: ConfigurationClassEnhancer.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public int accept(Method method) {
	for (int i = 0; i < this.callbacks.length; i++) {
		Callback callback = this.callbacks[i];
		if (!(callback instanceof ConditionalCallback) || ((ConditionalCallback) callback).isMatch(method)) {
			return i;
		}
	}
	throw new IllegalStateException("No callback available for method " + method.getName());
}
 
Example #27
Source File: ConfigurationClassEnhancer.java    From spring-analysis-note with MIT License 5 votes vote down vote up
public ConditionalCallbackFilter(Callback[] callbacks) {
	this.callbacks = callbacks;
	this.callbackTypes = new Class<?>[callbacks.length];
	for (int i = 0; i < callbacks.length; i++) {
		this.callbackTypes[i] = callbacks[i].getClass();
	}
}
 
Example #28
Source File: CglibAopProxy.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
private Callback[] getCallbacks(Class<?> rootClass) throws Exception {
	// Parameters used for optimization choices...
	boolean exposeProxy = this.advised.isExposeProxy();
	boolean isFrozen = this.advised.isFrozen();
	boolean isStatic = this.advised.getTargetSource().isStatic();

	// Choose an "aop" interceptor (used for AOP calls).
	Callback aopInterceptor = new DynamicAdvisedInterceptor(this.advised);

	// Choose a "straight to target" interceptor. (used for calls that are
	// unadvised but can return this). May be required to expose the proxy.
	Callback targetInterceptor;
	if (exposeProxy) {
		targetInterceptor = isStatic ?
				new StaticUnadvisedExposedInterceptor(this.advised.getTargetSource().getTarget()) :
				new DynamicUnadvisedExposedInterceptor(this.advised.getTargetSource());
	}
	else {
		targetInterceptor = isStatic ?
				new StaticUnadvisedInterceptor(this.advised.getTargetSource().getTarget()) :
				new DynamicUnadvisedInterceptor(this.advised.getTargetSource());
	}

	// Choose a "direct to target" dispatcher (used for
	// unadvised calls to static targets that cannot return this).
	Callback targetDispatcher = isStatic ?
			new StaticDispatcher(this.advised.getTargetSource().getTarget()) : new SerializableNoOp();

	Callback[] mainCallbacks = new Callback[] {
			aopInterceptor,  // for normal advice
			targetInterceptor,  // invoke target without considering advice, if optimized
			new SerializableNoOp(),  // no override for methods mapped to this
			targetDispatcher, this.advisedDispatcher,
			new EqualsInterceptor(this.advised),
			new HashCodeInterceptor(this.advised)
	};

	Callback[] callbacks;

	// If the target is a static one and the advice chain is frozen,
	// then we can make some optimizations by sending the AOP calls
	// direct to the target using the fixed chain for that method.
	if (isStatic && isFrozen) {
		Method[] methods = rootClass.getMethods();
		Callback[] fixedCallbacks = new Callback[methods.length];
		this.fixedInterceptorMap = new HashMap<String, Integer>(methods.length);

		// TODO: small memory optimization here (can skip creation for methods with no advice)
		for (int x = 0; x < methods.length; x++) {
			List<Object> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(methods[x], rootClass);
			fixedCallbacks[x] = new FixedChainStaticTargetInterceptor(
					chain, this.advised.getTargetSource().getTarget(), this.advised.getTargetClass());
			this.fixedInterceptorMap.put(methods[x].toString(), x);
		}

		// Now copy both the callbacks from mainCallbacks
		// and fixedCallbacks into the callbacks array.
		callbacks = new Callback[mainCallbacks.length + fixedCallbacks.length];
		System.arraycopy(mainCallbacks, 0, callbacks, 0, mainCallbacks.length);
		System.arraycopy(fixedCallbacks, 0, callbacks, mainCallbacks.length, fixedCallbacks.length);
		this.fixedInterceptorOffset = mainCallbacks.length;
	}
	else {
		callbacks = mainCallbacks;
	}
	return callbacks;
}
 
Example #29
Source File: MockHelper.java    From COLA with GNU Lesser General Public License v2.1 4 votes vote down vote up
public static Object createMockFor(Class clazz, MethodInterceptor interceptor){
    Class proxyCls = createMockClass(clazz);
    Factory proxy = (Factory)newInstance(proxyCls);
    proxy.setCallbacks(new Callback[] {interceptor});
    return proxy;
}
 
Example #30
Source File: CglibAopProxy.java    From java-technology-stack with MIT License 4 votes vote down vote up
private Callback[] getCallbacks(Class<?> rootClass) throws Exception {
	// Parameters used for optimization choices...
	boolean exposeProxy = this.advised.isExposeProxy();
	boolean isFrozen = this.advised.isFrozen();
	boolean isStatic = this.advised.getTargetSource().isStatic();

	// Choose an "aop" interceptor (used for AOP calls).
	Callback aopInterceptor = new DynamicAdvisedInterceptor(this.advised);

	// Choose a "straight to target" interceptor. (used for calls that are
	// unadvised but can return this). May be required to expose the proxy.
	Callback targetInterceptor;
	if (exposeProxy) {
		targetInterceptor = (isStatic ?
				new StaticUnadvisedExposedInterceptor(this.advised.getTargetSource().getTarget()) :
				new DynamicUnadvisedExposedInterceptor(this.advised.getTargetSource()));
	}
	else {
		targetInterceptor = (isStatic ?
				new StaticUnadvisedInterceptor(this.advised.getTargetSource().getTarget()) :
				new DynamicUnadvisedInterceptor(this.advised.getTargetSource()));
	}

	// Choose a "direct to target" dispatcher (used for
	// unadvised calls to static targets that cannot return this).
	Callback targetDispatcher = (isStatic ?
			new StaticDispatcher(this.advised.getTargetSource().getTarget()) : new SerializableNoOp());

	Callback[] mainCallbacks = new Callback[] {
			aopInterceptor,  // for normal advice
			targetInterceptor,  // invoke target without considering advice, if optimized
			new SerializableNoOp(),  // no override for methods mapped to this
			targetDispatcher, this.advisedDispatcher,
			new EqualsInterceptor(this.advised),
			new HashCodeInterceptor(this.advised)
	};

	Callback[] callbacks;

	// If the target is a static one and the advice chain is frozen,
	// then we can make some optimizations by sending the AOP calls
	// direct to the target using the fixed chain for that method.
	if (isStatic && isFrozen) {
		Method[] methods = rootClass.getMethods();
		Callback[] fixedCallbacks = new Callback[methods.length];
		this.fixedInterceptorMap = new HashMap<>(methods.length);

		// TODO: small memory optimization here (can skip creation for methods with no advice)
		for (int x = 0; x < methods.length; x++) {
			List<Object> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(methods[x], rootClass);
			fixedCallbacks[x] = new FixedChainStaticTargetInterceptor(
					chain, this.advised.getTargetSource().getTarget(), this.advised.getTargetClass());
			this.fixedInterceptorMap.put(methods[x].toString(), x);
		}

		// Now copy both the callbacks from mainCallbacks
		// and fixedCallbacks into the callbacks array.
		callbacks = new Callback[mainCallbacks.length + fixedCallbacks.length];
		System.arraycopy(mainCallbacks, 0, callbacks, 0, mainCallbacks.length);
		System.arraycopy(fixedCallbacks, 0, callbacks, mainCallbacks.length, fixedCallbacks.length);
		this.fixedInterceptorOffset = mainCallbacks.length;
	}
	else {
		callbacks = mainCallbacks;
	}
	return callbacks;
}