Java Code Examples for javassist.util.proxy.ProxyFactory#setInterfaces()

The following examples show how to use javassist.util.proxy.ProxyFactory#setInterfaces() . 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: JavassistClientProxyFactory.java    From bowman with Apache License 2.0 6 votes vote down vote up
private static <T> T createProxyInstance(Class<T> entityType, MethodHandlerChain handlerChain) {
	ProxyFactory factory = new ProxyFactory();
	if (ProxyFactory.isProxyClass(entityType)) {
		factory.setInterfaces(getNonProxyInterfaces(entityType));
		factory.setSuperclass(entityType.getSuperclass());
	}
	else {
		factory.setSuperclass(entityType);
	}
	factory.setFilter(handlerChain);
	
	Class<?> clazz = factory.createClass();
	T proxy = instantiateClass(clazz);
	((Proxy) proxy).setHandler(handlerChain);
	return proxy;
}
 
Example 2
Source File: JavassistLazyInitializer.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
public static Class getProxyFactory(
		Class persistentClass,
        Class[] interfaces) throws HibernateException {
	// note: interfaces is assumed to already contain HibernateProxy.class

	try {
		ProxyFactory factory = new ProxyFactory();
		factory.setSuperclass( interfaces.length == 1 ? persistentClass : null );
		factory.setInterfaces( interfaces );
		factory.setFilter( FINALIZE_FILTER );
		return factory.createClass();
	}
	catch ( Throwable t ) {
		LogFactory.getLog( BasicLazyInitializer.class ).error(
				"Javassist Enhancement failed: "
				+ persistentClass.getName(), t
		);
		throw new HibernateException(
				"Javassist Enhancement failed: "
				+ persistentClass.getName(), t
		);
	}
}
 
Example 3
Source File: ProxyBuilder.java    From docx-stamper with MIT License 6 votes vote down vote up
/**
 * Creates a proxy object out of the specified root object and the specified interfaces
 * and implementations.
 *
 * @return a proxy object that is still of type T but additionally implements all specified
 * interfaces.
 * @throws ProxyException if the proxy could not be created.
 */
public T build() throws ProxyException {

  if (this.root == null) {
    throw new IllegalArgumentException("root must not be null!");
  }

  if (this.interfacesToImplementations.isEmpty()) {
    // nothing to proxy
    return this.root;
  }

  try {
    ProxyMethodHandler methodHandler = new ProxyMethodHandler(root,
            interfacesToImplementations);
    ProxyFactory proxyFactory = new ProxyFactory();
    proxyFactory.setSuperclass(root.getClass());
    proxyFactory.setInterfaces(interfacesToImplementations.keySet().toArray(new Class[]{}));
    return (T) proxyFactory.create(new Class[0], new Object[0], methodHandler);
  } catch (Exception e) {
    throw new ProxyException(e);
  }
}
 
Example 4
Source File: TransactionalClassProxy.java    From seed with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * Create a transactional proxy around the provided {@link TransactionalLink}.
 *
 * @param <T>               the interface used to create the proxy.
 * @param clazz             the class representing the transacted resource.
 * @param transactionalLink the link to access the instance of the transacted resource.
 * @return the proxy.
 */
@SuppressWarnings("unchecked")
public static <T> T create(Class<T> clazz, final TransactionalLink<T> transactionalLink) {
    try {
        ProxyFactory factory = new ProxyFactory();
        factory.setSuperclass(clazz);
        if (AutoCloseable.class.isAssignableFrom(clazz)) {
            factory.setInterfaces(new Class<?>[]{IgnoreAutoCloseable.class});
        }
        factory.setFilter(method -> !method.getDeclaringClass().equals(Object.class));
        return (T) factory.create(new Class<?>[0], new Object[0], new TransactionalClassProxy<>(transactionalLink));
    } catch (NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) {
        throw SeedException.wrap(e, TransactionErrorCode.UNABLE_TO_CREATE_TRANSACTIONAL_PROXY).put("class",
                clazz.getName());
    }
}
 
Example 5
Source File: JavassistProxifier.java    From vraptor4 with Apache License 2.0 6 votes vote down vote up
@Override
public <T> T proxify(Class<T> type, MethodInvocation<? super T> handler) {
	final ProxyFactory factory = new ProxyFactory();
	factory.setFilter(IGNORE_BRIDGE_AND_OBJECT_METHODS);
	Class<?> rawType = extractRawType(type);

	if (type.isInterface()) {
		factory.setInterfaces(new Class[] { rawType });
	} else {
		factory.setSuperclass(rawType);
	}

	Object instance = createInstance(type, handler, factory);
	logger.debug("a proxy for {} was created as {}", type, instance.getClass());

	return (T) instance;
}
 
Example 6
Source File: JavassistPartialObjectFactory.java    From spearal-java with Apache License 2.0 5 votes vote down vote up
@Override
public Class<?> createValue(SpearalContext context, Class<?> key, Object unused) {
	context.getSecurizer().checkDecodable(key);
	
	ProxyFactory proxyFactory = new ProxyFactory();
	proxyFactory.setFilter(new PartialObjectFilter(context, key));
	proxyFactory.setSuperclass(key);
	proxyFactory.setInterfaces(new Class<?>[] { ExtendedPartialObjectProxy.class });
	return proxyFactory.createClass();
}
 
Example 7
Source File: JavassistClientProxyFactoryTest.java    From bowman with Apache License 2.0 4 votes vote down vote up
private static <T> T instantiateProxyOfInterfaceType(Class<T> type) throws Exception {
	ProxyFactory factory = new ProxyFactory();
	factory.setInterfaces(new Class[] {type});
	return instantiate(factory.createClass());
}
 
Example 8
Source File: JavassistLazyInitializer.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
public static HibernateProxy getProxy(
		final String entityName,
        final Class persistentClass,
        final Class[] interfaces,
        final Method getIdentifierMethod,
        final Method setIdentifierMethod,
        AbstractComponentType componentIdType,
        final Serializable id,
        final SessionImplementor session) throws HibernateException {
	// note: interface is assumed to already contain HibernateProxy.class
	try {
		final JavassistLazyInitializer instance = new JavassistLazyInitializer(
				entityName,
		        persistentClass,
		        interfaces,
		        id,
		        getIdentifierMethod,
		        setIdentifierMethod,
		        componentIdType,
		        session
		);
		ProxyFactory factory = new ProxyFactory();
		factory.setSuperclass( interfaces.length == 1 ? persistentClass : null );
		factory.setInterfaces( interfaces );
		factory.setFilter( FINALIZE_FILTER );
		Class cl = factory.createClass();
		final HibernateProxy proxy = ( HibernateProxy ) cl.newInstance();
		( ( ProxyObject ) proxy ).setHandler( instance );
		instance.constructed = true;
		return proxy;
	}
	catch ( Throwable t ) {
		LogFactory.getLog( BasicLazyInitializer.class ).error(
				"Javassist Enhancement failed: " + entityName, t
		);
		throw new HibernateException(
				"Javassist Enhancement failed: "
				+ entityName, t
		);
	}
}
 
Example 9
Source File: ClassByImplementationBenchmark.java    From byte-buddy with Apache License 2.0 4 votes vote down vote up
/**
 * Performs a benchmark of an interface implementation using javassist proxies.
 *
 * @return The created instance, in order to avoid JIT removal.
 * @throws java.lang.Exception If the reflective invocation causes an exception.
 */
@Benchmark
public ExampleInterface benchmarkJavassist() throws Exception {
    ProxyFactory proxyFactory = new ProxyFactory() {
        protected ClassLoader getClassLoader() {
            return newClassLoader();
        }
    };
    proxyFactory.setUseCache(false);
    proxyFactory.setUseWriteReplace(false);
    proxyFactory.setSuperclass(Object.class);
    proxyFactory.setInterfaces(new Class<?>[]{baseClass});
    proxyFactory.setFilter(new MethodFilter() {
        public boolean isHandled(Method method) {
            return true;
        }
    });
    @SuppressWarnings("unchecked")
    Object instance = proxyFactory.createClass().getDeclaredConstructor().newInstance();
    ((javassist.util.proxy.Proxy) instance).setHandler(new MethodHandler() {
        public Object invoke(Object self,
                             Method thisMethod,
                             Method proceed,
                             Object[] args) throws Throwable {
            Class<?> returnType = thisMethod.getReturnType();
            if (returnType.isPrimitive()) {
                if (returnType == boolean.class) {
                    return defaultBooleanValue;
                } else if (returnType == byte.class) {
                    return defaultByteValue;
                } else if (returnType == short.class) {
                    return defaultShortValue;
                } else if (returnType == char.class) {
                    return defaultCharValue;
                } else if (returnType == int.class) {
                    return defaultIntValue;
                } else if (returnType == long.class) {
                    return defaultLongValue;
                } else if (returnType == float.class) {
                    return defaultFloatValue;
                } else {
                    return defaultDoubleValue;
                }
            } else {
                return defaultReferenceValue;
            }
        }
    });
    return (ExampleInterface) instance;
}