Java Code Examples for net.sf.cglib.proxy.Enhancer#create()

The following examples show how to use net.sf.cglib.proxy.Enhancer#create() . 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: 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 2
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 3
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 4
Source File: CGlibProxyFactory.java    From blog with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
	public <T> T createProxy(T targetObject, Callback callback) {
		if (targetObject == null) {
			throw new IllegalArgumentException("targetObject must not be null");
		}
		if (callback == null) {
			throw new IllegalArgumentException("callback must not be null");
		}
		Class<?> targetType = targetObject.getClass();
		return (T) Enhancer.create(targetType, callback);
//		Class<?> superclass = targetType.getSuperclass();
//		List<Class<?>> allInterfaces = ClassUtils.getAllInterfaces(targetType);
//		Class<?>[] allInterfacesAsArray = (Class<?>[]) allInterfaces.toArray(new Class<?>[allInterfaces.size()]);
//		Enhancer enhancer = new Enhancer();
//		enhancer.setSuperclass(superclass);
//		enhancer.setInterfaces(allInterfacesAsArray);
//		enhancer.setCallback(callback);
//		enhancer.setUseFactory(true);
//
//		Object proxyObject = enhancer.create();
//		return (T) proxyObject;
	}
 
Example 5
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 6
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 7
Source File: CglibDynamicProxy.java    From AndroidFrame with Apache License 2.0 5 votes vote down vote up
/**
 * 创建代理对象
 * @param target 被代理的对象
 * @return
 */
public Object getProxyInstance(Object target){
    this.target = target;
    // 声明增强类实例
    Enhancer enhancer = new Enhancer();
    // 设置被代理类字节码,CGLIB根据字节码生成被代理类的子类
    enhancer.setSuperclass(this.target.getClass());
    // 设置要代理的拦截器,回调函数,即一个方法拦截   new MethodInterceptor()
    enhancer.setCallback(this);
    // 创建代理对象 实例
    return enhancer.create();
}
 
Example 8
Source File: UserServiceProxy2.java    From blog-sample with Apache License 2.0 5 votes vote down vote up
public UserService getUserServiceProxy() {
    // 生成代理对象
    Enhancer enhancer = new Enhancer();
    // 设置对谁进行代理
    enhancer.setSuperclass(UserServiceImpl.class);
    // 代理要做什么
    enhancer.setCallback(this);
    // 创建代理对象
    UserService us = (UserService) enhancer.create();

    return us;
}
 
Example 9
Source File: TransactionInterceptor.java    From JavaBase with MIT License 5 votes vote down vote up
public Object createProxy() {
  Enhancer enhancer = new Enhancer();
  //设置代理类为目标类的子类
  enhancer.setSuperclass(this.target.getClass());
  //设置拦截器为回调函数
  enhancer.setCallback(this);
  return enhancer.create();
}
 
Example 10
Source File: MvcCglibProxy.java    From Mars-Java with MIT License 5 votes vote down vote up
/**
 * 获取代理对象
 * @param clazz  bean的class
 * @return 对象
 */
public Object getProxy(Class<?> clazz) {
    this.cls = clazz;

	enhancer = new Enhancer();
	// 设置需要创建子类的类
	enhancer.setSuperclass(clazz);
	enhancer.setCallback(this);
	// 通过字节码技术动态创建子类实例
	return enhancer.create();
}
 
Example 11
Source File: DynamicProxyPerfClient.java    From JavaDesignPattern with Apache License 2.0 5 votes vote down vote up
private static void testCglibCreation() {
  long start = System.currentTimeMillis();
  for (int i = 0; i < creation; i++) {
    MethodInterceptor methodInterceptor = new SubjectInterceptor();
    Enhancer enhancer = new Enhancer();
    enhancer.setSuperclass(ConcreteSubject.class);
    enhancer.setCallback(methodInterceptor);
    enhancer.create();
  }
  long stop = System.currentTimeMillis();
  LOG.info("cglib creation time : {} ms", stop - start);
}
 
Example 12
Source File: MonitorRenderFactory.java    From gecco with MIT License 5 votes vote down vote up
@Override
public JsonRender createJsonRender() {
	Enhancer enhancer = new Enhancer();
	enhancer.setSuperclass(JsonRender.class);
	enhancer.setCallback(new RenderMointorIntercetor());
	return (JsonRender)enhancer.create();
}
 
Example 13
Source File: BrpcProxy.java    From brpc-java with Apache License 2.0 5 votes vote down vote up
public static <T> T getProxy(RpcClient rpcClient, Class clazz, NamingOptions namingOptions) {
    rpcClient.setServiceInterface(clazz, namingOptions);
    Enhancer en = new Enhancer();
    en.setSuperclass(clazz);
    en.setCallback(new BrpcProxy(rpcClient, clazz));
    return (T) en.create();
}
 
Example 14
Source File: CglibThrowableRendererTest.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
@Test
public void testDoRendere() {
    SampleClass sampleClass = (SampleClass)Enhancer.create(SampleClass.class, new MyInvocationHandler());
    try {
        sampleClass.theFirstMethodThatCapturesAnException();
    } catch (Exception e) {
        String[] exceptions = cglibThrowableRenderer.doRender(e);
        assertThatTheTraceListDoesNotContainsCgLibLogs(exceptions);
    }
}
 
Example 15
Source File: CGLIBEnhancedConverter.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private Object create(final Enhancer enhancer, List callbacks, boolean useFactory) {
    Object result = enhancer.create();
    if (useFactory) {
        ((Factory)result).setCallbacks((Callback[])callbacks.toArray(new Callback[callbacks
            .size()]));
    }
    return result;
}
 
Example 16
Source File: CglibProxyHelper.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Override
protected Object getProxyInternal(ClassLoader loader, Class<?>[] interfaces,
                                  final java.lang.reflect.InvocationHandler h) {

    Class<?> superClass = null;
    List<Class<?>> theInterfaces = new ArrayList<>();

    for (Class<?> c : interfaces) {
        if (!c.isInterface()) {
            if (superClass != null) {
                throw new IllegalArgumentException("Only a single superclass is supported");
            }
            superClass = c;
        } else {
            theInterfaces.add(c);
        }
    }
    if (superClass != null) {
        Enhancer enhancer = new Enhancer();
        enhancer.setClassLoader(loader);
        enhancer.setSuperclass(superClass);
        enhancer.setInterfaces(theInterfaces.toArray(new Class<?>[0]));
        enhancer.setCallback(new MethodInterceptor() {

            public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy)
                throws Throwable {
                return h.invoke(obj, method, args);
            }

        });
        return enhancer.create();
    }
    return super.getProxyInternal(loader, interfaces, h);
}
 
Example 17
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 18
Source File: CglibProxy.java    From sisyphus with Apache License 2.0 5 votes vote down vote up
@Override
public Object proxy() {
    Enhancer enhancer = new Enhancer();
    //目标对象类
    enhancer.setSuperclass(target.getClass());
    enhancer.setCallback(this);
    //通过字节码技术创建目标对象类的子类实例作为代理
    return enhancer.create();
}
 
Example 19
Source File: ProxyManager.java    From bfmvc with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
public static <T> T createProxy(final Class<?> targetClass, final List<Proxy> proxyList){
    return (T) Enhancer.create(targetClass,
            (MethodInterceptor) (targetObject, targetMethod, methodParams, methodProxy) ->
                    new ProxyChain(targetClass, targetObject, targetMethod, methodProxy, methodParams, proxyList));
}
 
Example 20
Source File: GenericDaoBase.java    From cosmic with Apache License 2.0 4 votes vote down vote up
protected GenericDaoBase() {
    super();
    final Type t = getClass().getGenericSuperclass();
    if (t instanceof ParameterizedType) {
        _entityBeanType = (Class<T>) ((ParameterizedType) t).getActualTypeArguments()[0];
    } else if (((Class<?>) t).getGenericSuperclass() instanceof ParameterizedType) {
        _entityBeanType = (Class<T>) ((ParameterizedType) ((Class<?>) t).getGenericSuperclass()).getActualTypeArguments()[0];
    } else {
        _entityBeanType = (Class<T>) ((ParameterizedType) ((Class<?>) ((Class<?>) t).getGenericSuperclass()).getGenericSuperclass()).getActualTypeArguments()[0];
    }

    s_daoMaps.put(_entityBeanType.getCanonicalName(), this);
    final Class<?>[] interfaceClasses = _entityBeanType.getInterfaces();
    if (interfaceClasses != null) {
        for (final Class<?> interfaceClass : interfaceClasses) {
            s_daoMaps.put(interfaceClass.getCanonicalName(), this);
        }
    }
    logDetectedDaos();

    _table = DbUtil.getTableName(_entityBeanType);

    final SqlGenerator generator = new SqlGenerator(_entityBeanType);
    _partialSelectSql = generator.buildSelectSql(false);
    _count = generator.buildCountSql();
    _distinctIdSql = generator.buildDistinctIdSql();
    _partialQueryCacheSelectSql = generator.buildSelectSql(true);
    _embeddedFields = generator.getEmbeddedFields();
    _insertSqls = generator.buildInsertSqls();
    final Pair<StringBuilder, Map<String, Object>> dc = generator.buildDiscriminatorClause();
    _discriminatorClause = dc.first().length() == 0 ? null : dc.first();
    _discriminatorValues = dc.second();

    _idAttributes = generator.getIdAttributes();
    _idField = _idAttributes.get(_table).length > 0 ? _idAttributes.get(_table)[0].field : null;

    _tables = generator.buildTableReferences();

    _allAttributes = generator.getAllAttributes();
    _allColumns = generator.getAllColumns();

    _selectByIdSql = buildSelectByIdSql(createPartialSelectSql(null, true));
    _removeSql = generator.buildRemoveSql();
    _deleteSqls = generator.buildDeleteSqls();
    _removed = generator.getRemovedAttribute();
    _tgs = generator.getTableGenerators();
    _ecAttributes = generator.getElementCollectionAttributes();

    TableGenerator tg = this.getClass().getAnnotation(TableGenerator.class);
    if (tg != null) {
        _tgs.put(tg.name(), tg);
    }
    tg = this.getClass().getSuperclass().getAnnotation(TableGenerator.class);
    if (tg != null) {
        _tgs.put(tg.name(), tg);
    }

    final Callback[] callbacks = new Callback[]{NoOp.INSTANCE, new UpdateBuilder(this)};

    _enhancer = new Enhancer();
    _enhancer.setSuperclass(_entityBeanType);
    _enhancer.setCallbackFilter(s_callbackFilter);
    _enhancer.setCallbacks(callbacks);
    _factory = (Factory) _enhancer.create();

    _searchEnhancer = new Enhancer();
    _searchEnhancer.setSuperclass(_entityBeanType);
    _searchEnhancer.setCallback(new UpdateBuilder(this));

    if (s_logger.isTraceEnabled()) {
        s_logger.trace("Select SQL: " + _partialSelectSql.first().toString());
        s_logger.trace("Remove SQL: " + (_removeSql != null ? _removeSql.first() : "No remove sql"));
        s_logger.trace("Select by Id SQL: " + _selectByIdSql);
        s_logger.trace("Table References: " + _tables);
        s_logger.trace("Insert SQLs:");
        for (final Pair<String, Attribute[]> insertSql : _insertSqls) {
            s_logger.trace(insertSql.first());
        }

        s_logger.trace("Delete SQLs");
        for (final Pair<String, Attribute[]> deletSql : _deleteSqls) {
            s_logger.trace(deletSql.first());
        }

        s_logger.trace("Collection SQLs");
        for (final Attribute attr : _ecAttributes) {
            final EcInfo info = (EcInfo) attr.attache;
            s_logger.trace(info.insertSql);
            s_logger.trace(info.selectSql);
        }
    }

    setRunLevel(ComponentLifecycle.RUN_LEVEL_SYSTEM);
}