Example usage for org.springframework.cglib.proxy Enhancer create

List of usage examples for org.springframework.cglib.proxy Enhancer create

Introduction

In this page you can find the example usage for org.springframework.cglib.proxy Enhancer create.

Prototype

public Object create() 

Source Link

Document

Generate a new class if necessary and uses the specified callbacks (if any) to create a new object instance.

Usage

From source file:net.kaczmarzyk.spring.data.jpa.web.EnhancerUtil.java

@SuppressWarnings("unchecked")
static <T> T wrapWithIfaceImplementation(final Class<T> iface, final Specification<Object> targetSpec) {
    Enhancer enhancer = new Enhancer();
    enhancer.setInterfaces(new Class[] { iface });
    enhancer.setCallback(new MethodInterceptor() {
        @Override// www . ja  v  a 2s  . c om
        public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
            if ("toString".equals(method.getName())) {
                return iface.getSimpleName() + "[" + proxy.invoke(targetSpec, args) + "]";
            }
            return proxy.invoke(targetSpec, args);
        }
    });

    return (T) enhancer.create();
}

From source file:io.syndesis.runtime.Recordings.java

static public <T> T recorder(Object object, Class<T> as) {
    if (as.isInterface()) {
        // If it's just an interface, use standard java reflect proxying
        return as.cast(Proxy.newProxyInstance(as.getClassLoader(), new Class[] { as },
                new RecordingInvocationHandler(object)));
    }//from   w  w  w.  j  a va  2  s  . com

    // If it's a class then use gclib to implement a subclass to implement proxying
    RecordingInvocationHandler ih = new RecordingInvocationHandler(object);
    Enhancer enhancer = new Enhancer();
    enhancer.setSuperclass(as);
    enhancer.setInterfaces(new Class[] { RecordingProxy.class });
    enhancer.setCallback(new org.springframework.cglib.proxy.InvocationHandler() {
        @Override
        public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
            return ih.invoke(o, method, objects);
        }
    });
    return as.cast(enhancer.create());
}

From source file:org.agiso.core.i18n.util.I18nUtils.java

@SuppressWarnings({ "unchecked", "rawtypes" })
public static <T> Recorder<T> create(Class<T> cls) {
    Enhancer enhancer = new Enhancer();
    enhancer.setSuperclass(cls);/*from www.j a  va 2 s  .c  o  m*/
    final RecordingObject recordingObject = new RecordingObject();

    enhancer.setCallback(recordingObject);
    return new Recorder((T) enhancer.create(), recordingObject);
}

From source file:com.newtranx.util.cassandra.spring.AccessorScannerConfigurer.java

@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory context) throws BeansException {
    ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(
            false) {//from   w  w  w.  j  a  v  a 2  s .co  m

        @Override
        protected boolean isCandidateComponent(AnnotatedBeanDefinition beanDefinition) {
            return beanDefinition.getMetadata().isInterface();
        }

    };
    scanner.addIncludeFilter(new AnnotationTypeFilter(Accessor.class));
    for (BeanDefinition bd : scanner.findCandidateComponents(basePackage)) {
        Class<?> accessorCls;
        try {
            accessorCls = Class.forName(bd.getBeanClassName());
        } catch (ClassNotFoundException e) {
            throw new AssertionError(e);
        }
        log.info("Creating proxy accessor: " + accessorCls.getName());
        MethodInterceptor interceptor = new MethodInterceptor() {

            private final Lazy<?> target = new Lazy<>(() -> {
                log.info("Creating actual accessor: " + accessorCls.getName());
                Session session;
                if (AccessorScannerConfigurer.this.session == null)
                    session = mainContext.getBean(Session.class);
                else
                    session = AccessorScannerConfigurer.this.session;
                MappingManager mappingManager = new MappingManager(session);
                return mappingManager.createAccessor(accessorCls);
            });

            @Override
            public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy)
                    throws Throwable {
                if ("toString".equals(method.getName())) {
                    return accessorCls.getName();
                }
                return method.invoke(target.get(), args);
            }

        };
        Enhancer enhancer = new Enhancer();
        enhancer.setInterfaces(new Class<?>[] { accessorCls });
        enhancer.setCallback(interceptor);
        Object bean = enhancer.create();
        String beanName = StringUtils.uncapitalize(accessorCls.getSimpleName());
        context.registerSingleton(beanName, bean);
        log.info("Bean registed, name=" + beanName + ", bean=" + bean.toString());
    }
}

From source file:cat.albirar.framework.proxy.ProxyFactory.java

/**
 * Create a proxy for the indicated type.
 * @param handler The handler/*ww w  . j  a  va 2s .c  om*/
 * @param type The type, should to be a concrete class type
 * @return The proxy
 */
@SuppressWarnings("unchecked")
private <T> T newProxyForConcreteClass(org.springframework.cglib.proxy.Callback handler, Class<T> type) {
    Enhancer enhancer;

    Assert.isTrue(!Modifier.isAbstract(type.getModifiers()), "The type should to be a concrete class");

    enhancer = new Enhancer();
    enhancer.setSuperclass(type);
    enhancer.setClassLoader(type.getClassLoader());
    enhancer.setCallback(handler);
    return (T) enhancer.create();
}

From source file:io.neba.core.resourcemodels.mapping.ResourceToModelMapperTest.java

private void withSpringAopProxyFor(Class<TestModel> superclass) throws Exception {
    Enhancer enhancer = new Enhancer();
    enhancer.setSuperclass(superclass);/*w  w  w . j av  a2s  .c om*/
    enhancer.setCallback(NoOp.INSTANCE);
    enhancer.setInterfaces(new Class[] { Advised.class });
    Object enhanced = spy(enhancer.create());
    assertThat(enhanced).isNotNull();

    this.targetSource = mock(TargetSource.class);
    TestModel unwrappedBeanInstance = new TestModel();
    doReturn(this.targetSource).when((Advised) enhanced).getTargetSource();
    doReturn(unwrappedBeanInstance).when(this.targetSource).getTarget();

    this.model = (TestModel) enhanced;
}