javassist.util.proxy.ProxyFactory Java Examples

The following examples show how to use javassist.util.proxy.ProxyFactory. 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: ProxyUtils.java    From chrome-devtools-java-client with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a proxy class to a given abstract clazz supplied with invocation handler for
 * un-implemented/abstrat methods.
 *
 * @param clazz Proxy to class.
 * @param paramTypes Ctor param types.
 * @param args Ctor args.
 * @param invocationHandler Invocation handler.
 * @param <T> Class type.
 * @return Proxy instance.
 */
@SuppressWarnings("unchecked")
public static <T> T createProxyFromAbstract(
    Class<T> clazz, Class[] paramTypes, Object[] args, InvocationHandler invocationHandler) {
  ProxyFactory proxyFactory = new ProxyFactory();
  proxyFactory.setSuperclass(clazz);
  proxyFactory.setFilter(method -> Modifier.isAbstract(method.getModifiers()));
  try {
    return (T)
        proxyFactory.create(
            paramTypes,
            args,
            (o, method, method1, objects) -> invocationHandler.invoke(o, method, objects));
  } catch (Exception e) {
    LOGGER.error("Failed creating proxy from abstract class", e);
    throw new RuntimeException("Failed creating proxy from abstract class", e);
  }
}
 
Example #2
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 #3
Source File: ProxyHelper.java    From stevia with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@SuppressWarnings("rawtypes")
public static <T> T create(final Object obj, final ProxyCallback onSuccess, final ProxyCallback onException) throws Exception {
	ProxyFactory factory = new ProxyFactory();
	Class<T> origClass = (Class<T>) obj.getClass();
	factory.setSuperclass(origClass);
	Class clazz = factory.createClass();
	MethodHandler handler = new MethodHandler() {

		@Override
		public Object invoke(Object self, Method overridden, Method forwarder,
				Object[] args) throws Throwable {
			try {
				Object returnVal = overridden.invoke(obj, args);
				if (null != onSuccess) onSuccess.execute();
				return returnVal;
			} catch (Throwable tr) {
				if (null != onException) onException.execute();
				throw tr;
			}
		}
	};
	Object instance = clazz.newInstance();
	((ProxyObject) instance).setHandler(handler);
	return (T) instance;
}
 
Example #4
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 #5
Source File: TrivialClassCreationBenchmark.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
/**
 * Performs a benchmark for a trivial class creation using javassist proxies.
 *
 * @return The created instance, in order to avoid JIT removal.
 */
@Benchmark
public Class<?> benchmarkJavassist() {
    ProxyFactory proxyFactory = new ProxyFactory() {
        protected ClassLoader getClassLoader() {
            return newClassLoader();
        }
    };
    proxyFactory.setUseCache(false);
    proxyFactory.setUseWriteReplace(false);
    proxyFactory.setSuperclass(baseClass);
    proxyFactory.setFilter(new MethodFilter() {
        public boolean isHandled(Method method) {
            return false;
        }
    });
    return proxyFactory.createClass();
}
 
Example #6
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 #7
Source File: BootstrapProxyFactory.java    From dropwizard-guicey with MIT License 6 votes vote down vote up
/**
 * @param bootstrap dropwizard bootstrap object
 * @param context   guicey configuration context
 * @return dropwizard bootstrap proxy object
 */
@SuppressWarnings("unchecked")
public static Bootstrap create(final Bootstrap bootstrap, final ConfigurationContext context) {
    try {
        final ProxyFactory factory = new ProxyFactory();
        factory.setSuperclass(Bootstrap.class);
        final Class proxy = factory.createClass();

        final Bootstrap res = (Bootstrap) proxy.getConstructor(Application.class).newInstance(new Object[]{null});
        ((Proxy) res).setHandler((self, thisMethod, proceed, args) -> {
            // intercept only bundle addition
            if (thisMethod.getName().equals("addBundle")) {
                context.registerDropwizardBundles((ConfiguredBundle) args[0]);
                return null;
            }
            // other methods called as is
            return thisMethod.invoke(bootstrap, args);
        });
        return res;
    } catch (Exception e) {
        throw new IllegalStateException("Failed to create Bootstrap proxy", e);
    }
}
 
Example #8
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 #9
Source File: JavassistProxyFactory.java    From ymate-platform-v2 with Apache License 2.0 6 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public <T> T createProxy(final Class<?> targetClass, final List<IProxy> proxies) {
    ProxyFactory factory = new ProxyFactory();
    factory.setSuperclass(targetClass);
    Class<?> clazz = factory.createClass();
    try {
        Object targetObj = clazz.newInstance();
        ((ProxyObject) targetObj).setHandler(new MethodHandler() {
            @Override
            public Object invoke(final Object self, Method thisMethod, final Method proceed, final Object[] args) throws Throwable {
                return new AbstractProxyChain(JavassistProxyFactory.this, targetClass, self, thisMethod, args, proxies) {
                    @Override
                    protected Object doInvoke() throws Throwable {
                        return proceed.invoke(getTargetObject(), getMethodParams());
                    }
                }.doProxyChain();
            }
        });
        return (T) targetObj;
    } catch (Exception e) {
        throw new Error(e);
    }
}
 
Example #10
Source File: Partial.java    From FreeBuilder with Apache License 2.0 6 votes vote down vote up
/**
 * Constructs a partial instance of abstract type {@code cls}, passing {@code args} into its
 * constructor.
 *
 * <p>The returned object will throw an {@link UnsupportedOperationException} from any
 * unimplemented methods.
 */
public static <T> T of(Class<T> cls, Object... args) {
  checkIsValidPartial(cls);
  try {
    Constructor<?> constructor = cls.getDeclaredConstructors()[0];
    ProxyFactory factory = new ProxyFactory();
    factory.setSuperclass(cls);
    factory.setFilter(new MethodFilter() {
      @Override public boolean isHandled(Method m) {
        return Modifier.isAbstract(m.getModifiers());
      }
    });
    @SuppressWarnings("unchecked")
    T partial = (T) factory.create(
        constructor.getParameterTypes(), args, new ThrowingMethodHandler());
    return partial;
  } catch (Exception e) {
    throw new RuntimeException("Failed to instantiate " + cls, e);
  }
}
 
Example #11
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 #12
Source File: JavaHandlerModule.java    From org.openntf.domino with Apache License 2.0 5 votes vote down vote up
@Override
public Class<?> load(final Class<?> frameClass) throws Exception {
	final Class<?> handlerClass = getHandlerClass(frameClass);
	ProxyFactory proxyFactory = new ProxyFactory() {
		@Override
		protected ClassLoader getClassLoader() {

			return new URLClassLoader(new URL[0], handlerClass.getClassLoader());
		}
	};
	proxyFactory.setUseCache(false);
	proxyFactory.setSuperclass(handlerClass);
	return proxyFactory.createClass();
}
 
Example #13
Source File: JavassistProxifier.java    From vraptor4 with Apache License 2.0 5 votes vote down vote up
private <T> Object createInstance(Class<T> type, MethodInvocation<? super T> handler, ProxyFactory factory) {
	try {
		return factory.create(null, null, new MethodInvocationAdapter<>(handler));
	} catch (ReflectiveOperationException | IllegalArgumentException e) {
		logger.error("An error occurs when create a proxy for type " + type, e);
		throw new ProxyCreationException(e);
	}
}
 
Example #14
Source File: ClassByExtensionBenchmark.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * Performs a benchmark of a class extension using javassist proxies.
 *
 * @return The created instance, in order to avoid JIT removal.
 * @throws java.lang.Exception If the invocation causes an exception.
 */
@Benchmark
public ExampleClass benchmarkJavassist() throws Exception {
    ProxyFactory proxyFactory = new ProxyFactory() {
        protected ClassLoader getClassLoader() {
            return newClassLoader();
        }
    };
    proxyFactory.setUseCache(false);
    proxyFactory.setUseWriteReplace(false);
    proxyFactory.setSuperclass(baseClass);
    proxyFactory.setFilter(new MethodFilter() {
        public boolean isHandled(Method method) {
            return method.getDeclaringClass() == baseClass;
        }
    });
    @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 {
            return proceed.invoke(self, args);
        }
    });
    return (ExampleClass) instance;
}
 
Example #15
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 #16
Source File: TypesTest.java    From monasca-common with Apache License 2.0 5 votes vote down vote up
@Test(enabled = false)
public void shouldDeProxyJavassistProxy() {
  ProxyFactory proxyFactory = new ProxyFactory();
  proxyFactory.setSuperclass(ArrayList.class);
  Class<?> proxy = proxyFactory.createClass();

  assertEquals(Types.deProxy(proxy), ArrayList.class);
}
 
Example #17
Source File: ReflectionUtils.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static Class<?> getRealClass( Class<?> klass )
{
    if ( ProxyFactory.isProxyClass( klass ) )
    {
        klass = klass.getSuperclass();
    }

    while ( PersistentCollection.class.isAssignableFrom( klass ) )
    {
        klass = klass.getSuperclass();
    }

    return klass;
}
 
Example #18
Source File: AuditLogUtil.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static void infoWrapper( Logger log, String username, Object object, String action )
{
    if ( log.isInfoEnabled() )
    {
        if ( username != null && object instanceof IdentifiableObject )
        {
            IdentifiableObject idObject = (IdentifiableObject) object;
            StringBuilder builder = new StringBuilder();

            builder.append( "'" ).append( username ).append( "' " ).append( action );

            if ( !ProxyFactory.isProxyClass( object.getClass() ) )
            {
                builder.append( " " ).append( object.getClass().getName() );
            }
            else
            {
                builder.append( " " ).append( object.getClass().getSuperclass().getName() );
            }

            if ( idObject.getName() != null && !idObject.getName().isEmpty() )
            {
                builder.append( ", name: " ).append( idObject.getName() );
            }

            if ( idObject.getUid() != null && !idObject.getUid().isEmpty() )
            {
                builder.append( ", uid: " ).append( idObject.getUid() );
            }

            log.info( builder.toString() );
        }
    }
}
 
Example #19
Source File: Preheat.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static Class<?> getRealClass( Class<?> klass )
{
    if ( ProxyFactory.isProxyClass( klass ) )
    {
        klass = klass.getSuperclass();
    }

    return klass;
}
 
Example #20
Source File: TrackerPreheat.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static Class<?> getRealClass( Class<?> klass )
{
    if ( ProxyFactory.isProxyClass( klass ) )
    {
        klass = klass.getSuperclass();
    }

    return klass;
}
 
Example #21
Source File: DefaultLinkService.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private <T> void generateHref( T object, String hrefBase )
{
    if ( object == null || getSetter( object.getClass() ) == null )
    {
        return;
    }

    Class<?> klass = object.getClass();

    if ( ProxyFactory.isProxyClass( klass ) )
    {
        klass = klass.getSuperclass();
    }

    Schema schema = schemaService.getDynamicSchema( klass );

    if ( !schema.haveApiEndpoint() || schema.getProperty( "id" ) == null || schema.getProperty( "id" ).getGetterMethod() == null )
    {
        return;
    }

    Property id = schema.getProperty( "id" );

    try
    {
        Object value = id.getGetterMethod().invoke( object );

        if ( !String.class.isInstance( value ) )
        {
            log.warn( "id on object of type " + object.getClass().getName() + " does not return a String." );
            return;
        }

        Method setHref = getSetter( object.getClass() );
        setHref.invoke( object, hrefBase + schema.getRelativeApiEndpoint() + "/" + value );
    }
    catch ( InvocationTargetException | IllegalAccessException ignored )
    {
    }
}
 
Example #22
Source File: AbstractPropertyAwareMethodHandler.java    From bowman with Apache License 2.0 5 votes vote down vote up
private static Class getBeanType(Class clazz) {
	if (!ProxyFactory.isProxyClass(clazz)) {
		return clazz;
	}
	
	return clazz.getSuperclass();
}
 
Example #23
Source File: TestProxyResource.java    From jax-rs-pac4j with Apache License 2.0 5 votes vote down vote up
@Path("proxied/class")
public TestClassLevelResource proxiedResource() {
    try {
        final ProxyFactory factory = new ProxyFactory();
        factory.setSuperclass(TestClassLevelResource.class);
        final Proxy proxy = (Proxy) factory.createClass().newInstance();
        proxy.setHandler((self, overridden, proceed, args) -> {
            return proceed.invoke(self, args);
        });

        return (TestClassLevelResource) proxy;
    } catch (InstantiationException | IllegalAccessException e) {
        throw new AssertionError(e);
    }
}
 
Example #24
Source File: ProxyDetectionTest.java    From graphql-spqr with Apache License 2.0 5 votes vote down vote up
@Test
public void testJavassistProxy() throws IllegalAccessException, InstantiationException {
    ProxyFactory f = new ProxyFactory();
    f.setSuperclass(User.class);
    f.setFilter(m -> !m.getName().equals("finalize"));
    Class proxyClass = f.createClass();
    assertTrue(ClassUtils.isProxy(proxyClass));
}
 
Example #25
Source File: ClassUtilsTest.java    From reflection-util with Apache License 2.0 5 votes vote down vote up
private static <T> T createJavassistProxy(T object) {
	ProxyFactory factory = new ProxyFactory();
	factory.setSuperclass(object.getClass());
	@SuppressWarnings("unchecked")
	T proxy = (T) ClassUtils.createNewInstance(factory.createClass());
	return proxy;
}
 
Example #26
Source File: OutlineBuilder.java    From datamill with ISC License 4 votes vote down vote up
private static <T> Outline<T> buildOutline(Class<T> classToOutline, boolean camelCased) {
    ProxyFactory proxyFactory = new ProxyFactory();
    proxyFactory.setSuperclass(classToOutline);
    Class<? extends T> outlineClass = proxyFactory.createClass();
    return new OutlineImpl<>(objenesis.newInstance(outlineClass), camelCased);
}
 
Example #27
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 #28
Source File: ThriftClientImpl.java    From thrift-pool-client with Artistic License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 *
 * <p>
 * iface.
 * </p>
 */
@SuppressWarnings("unchecked")
@Override
public <X extends TServiceClient> X iface(Class<X> ifaceClass,
        Function<TTransport, TProtocol> protocolProvider, int hash) {
    List<ThriftServerInfo> servers = serverInfoProvider.get();
    if (servers == null || servers.isEmpty()) {
        throw new NoBackendException();
    }
    hash = Math.abs(hash);
    hash = Math.max(hash, 0);
    ThriftServerInfo selected = servers.get(hash % servers.size());
    logger.trace("get connection for [{}]->{} with hash:{}", ifaceClass, selected, hash);

    TTransport transport = poolProvider.getConnection(selected);
    TProtocol protocol = protocolProvider.apply(transport);

    ProxyFactory factory = new ProxyFactory();
    factory.setSuperclass(ifaceClass);
    factory.setFilter(m -> ThriftClientUtils.getInterfaceMethodNames(ifaceClass).contains(
            m.getName()));
    try {
        X x = (X) factory.create(new Class[] { org.apache.thrift.protocol.TProtocol.class },
                new Object[] { protocol });
        ((Proxy) x).setHandler((self, thisMethod, proceed, args) -> {
            boolean success = false;
            try {
                Object result = proceed.invoke(self, args);
                success = true;
                return result;
            } finally {
                if (success) {
                    poolProvider.returnConnection(selected, transport);
                } else {
                    poolProvider.returnBrokenConnection(selected, transport);
                }
            }
        });
        return x;
    } catch (NoSuchMethodException | IllegalArgumentException | InstantiationException
            | IllegalAccessException | InvocationTargetException e) {
        throw new RuntimeException("fail to create proxy.", e);
    }
}
 
Example #29
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 #30
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;
}