Example usage for java.lang Class getInterfaces

List of usage examples for java.lang Class getInterfaces

Introduction

In this page you can find the example usage for java.lang Class getInterfaces.

Prototype

public Class<?>[] getInterfaces() 

Source Link

Document

Returns the interfaces directly implemented by the class or interface represented by this object.

Usage

From source file:org.apache.hadoop.hbase.regionserver.RegionCoprocessorHost.java

@Override
public RegionEnvironment createEnvironment(Class<?> implClass, Coprocessor instance, int priority, int seq,
        Configuration conf) {/*w  w w.j  a  va2s .c om*/
    // Check if it's an Endpoint.
    // Due to current dynamic protocol design, Endpoint
    // uses a different way to be registered and executed.
    // It uses a visitor pattern to invoke registered Endpoint
    // method.
    for (Class<?> c : implClass.getInterfaces()) {
        if (CoprocessorService.class.isAssignableFrom(c)) {
            region.registerService(((CoprocessorService) instance).getService());
        }
    }
    ConcurrentMap<String, Object> classData;
    // make sure only one thread can add maps
    synchronized (sharedDataMap) {
        // as long as at least one RegionEnvironment holds on to its classData it will
        // remain in this map
        classData = (ConcurrentMap<String, Object>) sharedDataMap.get(implClass.getName());
        if (classData == null) {
            classData = new ConcurrentHashMap<String, Object>();
            sharedDataMap.put(implClass.getName(), classData);
        }
    }
    return new RegionEnvironment(instance, priority, seq, conf, region, rsServices, classData);
}

From source file:io.sinistral.proteus.server.tools.swagger.Reader.java

@SuppressWarnings("deprecation")
private Operation parseMethod(Class<?> cls, Method method, AnnotatedMethod annotatedMethod,
        List<Parameter> globalParameters, List<ApiResponse> classApiResponses, List<String> pathParamNames) {
    Operation operation = new Operation();
    if (annotatedMethod != null) {
        method = annotatedMethod.getAnnotated();
    }/*from  ww  w  .  j  av  a2  s  .com*/
    ApiOperation apiOperation = ReflectionUtils.getAnnotation(method, ApiOperation.class);
    ApiResponses responseAnnotation = ReflectionUtils.getAnnotation(method, ApiResponses.class);

    String operationId;
    // check if it's an inherited or implemented method.
    boolean methodInSuperType = false;
    if (!cls.isInterface()) {
        methodInSuperType = ReflectionUtils.findMethod(method, cls.getSuperclass()) != null;
    }
    if (!methodInSuperType) {
        for (Class<?> implementedInterface : cls.getInterfaces()) {
            methodInSuperType = ReflectionUtils.findMethod(method, implementedInterface) != null;
            if (methodInSuperType) {
                break;
            }
        }
    }
    if (!methodInSuperType) {
        operationId = method.getName();
    } else {
        operationId = this.getOperationId(method.getName());
    }

    String responseContainer = null;

    Type responseType = null;
    Map<String, Property> defaultResponseHeaders = new LinkedHashMap<String, Property>();

    if (apiOperation != null) {
        if (apiOperation.hidden()) {
            return null;
        }
        if (operationId == null) {
            operationId = apiOperation.nickname();
        }

        defaultResponseHeaders = parseResponseHeaders(apiOperation.responseHeaders());

        operation.summary(apiOperation.value()).description(apiOperation.notes());

        if (!isVoid(apiOperation.response())) {
            responseType = apiOperation.response();
        }
        if (!apiOperation.responseContainer().isEmpty()) {
            responseContainer = apiOperation.responseContainer();
        }
        List<SecurityRequirement> securities = new ArrayList<SecurityRequirement>();
        for (Authorization auth : apiOperation.authorizations()) {
            if (!auth.value().isEmpty()) {
                SecurityRequirement security = new SecurityRequirement();
                security.setName(auth.value());
                for (AuthorizationScope scope : auth.scopes()) {
                    if (!scope.scope().isEmpty()) {
                        security.addScope(scope.scope());
                    }
                }
                securities.add(security);
            }
        }
        for (SecurityRequirement sec : securities) {
            operation.security(sec);
        }
        if (!apiOperation.consumes().isEmpty()) {
            String[] consumesAr = ReaderUtils.splitContentValues(new String[] { apiOperation.consumes() });
            for (String consume : consumesAr) {
                operation.consumes(consume);
            }
        }
        if (!apiOperation.produces().isEmpty()) {
            String[] producesAr = ReaderUtils.splitContentValues(new String[] { apiOperation.produces() });
            for (String produce : producesAr) {
                operation.produces(produce);
            }
        }
    }

    /*
     * @TODO
     * Use apiOperation response class instead of unwrapping ServerResponse's inner type
     */

    if (apiOperation != null && StringUtils.isNotEmpty(apiOperation.responseReference())) {
        Response response = new Response().description(SUCCESSFUL_OPERATION);
        response.schema(new RefProperty(apiOperation.responseReference()));
        operation.addResponse(String.valueOf(apiOperation.code()), response);
    } else if (responseType == null) {
        // pick out response from method declaration
        LOGGER.debug("picking up response class from method {}", method);
        responseType = method.getGenericReturnType();
    }

    if (responseType != null) {
        final JavaType javaType = TypeFactory.defaultInstance().constructType(responseType);
        if (!isVoid(javaType)) {

            final Class<?> responseCls = javaType.getRawClass();

            if (responseCls != null) {
                if (responseCls.isAssignableFrom(ServerResponse.class)) {
                    responseType = javaType.containedType(0);
                } else if (responseCls.isAssignableFrom(CompletableFuture.class)) {
                    Class<?> futureCls = javaType.containedType(0).getRawClass();

                    if (futureCls.isAssignableFrom(ServerResponse.class)) {
                        final JavaType futureType = TypeFactory.defaultInstance()
                                .constructType(javaType.containedType(0));
                        responseType = futureType.containedType(0);
                    } else {
                        responseType = javaType.containedType(0);
                    }
                }
            }
        }
    }

    if (isValidResponse(responseType)) {
        final Property property = ModelConverters.getInstance().readAsProperty(responseType);
        if (property != null) {
            final Property responseProperty = ContainerWrapper.wrapContainer(responseContainer, property);
            final int responseCode = (apiOperation == null) ? 200 : apiOperation.code();
            operation.response(responseCode, new Response().description(SUCCESSFUL_OPERATION)
                    .schema(responseProperty).headers(defaultResponseHeaders));
            appendModels(responseType);
        }
    }

    operation.operationId(operationId);

    if (operation.getConsumes() == null || operation.getConsumes().isEmpty()) {
        final Consumes consumes = ReflectionUtils.getAnnotation(method, Consumes.class);
        if (consumes != null) {
            for (String mediaType : ReaderUtils.splitContentValues(consumes.value())) {
                operation.consumes(mediaType);
            }
        }
    }

    if (operation.getProduces() == null || operation.getProduces().isEmpty()) {
        final Produces produces = ReflectionUtils.getAnnotation(method, Produces.class);
        if (produces != null) {
            for (String mediaType : ReaderUtils.splitContentValues(produces.value())) {
                operation.produces(mediaType);
            }
        }
    }

    List<ApiResponse> apiResponses = new ArrayList<>();
    if (responseAnnotation != null) {
        apiResponses.addAll(Arrays.asList(responseAnnotation.value()));
    }

    Class<?>[] exceptionTypes = method.getExceptionTypes();
    for (Class<?> exceptionType : exceptionTypes) {
        ApiResponses exceptionResponses = ReflectionUtils.getAnnotation(exceptionType, ApiResponses.class);
        if (exceptionResponses != null) {
            apiResponses.addAll(Arrays.asList(exceptionResponses.value()));
        }
    }

    for (ApiResponse apiResponse : apiResponses) {
        addResponse(operation, apiResponse);
    }
    // merge class level @ApiResponse
    for (ApiResponse apiResponse : classApiResponses) {
        String key = (apiResponse.code() == 0) ? "default" : String.valueOf(apiResponse.code());
        if (operation.getResponses() != null && operation.getResponses().containsKey(key)) {
            continue;
        }
        addResponse(operation, apiResponse);
    }

    if (ReflectionUtils.getAnnotation(method, Deprecated.class) != null) {
        operation.setDeprecated(true);
    }

    // process parameters
    for (Parameter globalParameter : globalParameters) {

        LOGGER.debug("globalParameters TYPE: " + globalParameter);

        operation.parameter(globalParameter);
    }

    Annotation[][] paramAnnotations = ReflectionUtils.getParameterAnnotations(method);
    java.lang.reflect.Parameter[] methodParameters = method.getParameters();

    if (annotatedMethod == null) {
        Type[] genericParameterTypes = method.getGenericParameterTypes();

        for (int i = 0; i < genericParameterTypes.length; i++) {

            Type type = TypeFactory.defaultInstance().constructType(genericParameterTypes[i], cls);

            if (type.getTypeName().contains("Optional")
                    || type.getTypeName().contains("io.sinistral.proteus.server.ServerResponse")) {
                if (type instanceof com.fasterxml.jackson.databind.type.SimpleType) {
                    com.fasterxml.jackson.databind.type.SimpleType simpleType = (com.fasterxml.jackson.databind.type.SimpleType) type;

                    type = simpleType.containedType(0);
                }

            }

            if (type.equals(ServerRequest.class) || type.equals(HttpServerExchange.class)
                    || type.equals(HttpHandler.class)
                    || type.getTypeName().contains("io.sinistral.proteus.server.ServerResponse")) {
                continue;
            }

            List<Parameter> parameters = getParameters(type, Arrays.asList(paramAnnotations[i]),
                    methodParameters[i], pathParamNames);

            for (Parameter parameter : parameters) {
                operation.parameter(parameter);
            }
        }
    } else {
        for (int i = 0; i < annotatedMethod.getParameterCount(); i++) {
            AnnotatedParameter param = annotatedMethod.getParameter(i);

            if (param.getParameterType().equals(ServerRequest.class)
                    || param.getParameterType().equals(HttpServerExchange.class)
                    || param.getParameterType().equals(HttpHandler.class)
                    || param.getParameterType().getTypeName().contains("ServerResponse")) {
                continue;
            }

            Type type = TypeFactory.defaultInstance().constructType(param.getParameterType(), cls);

            List<Parameter> parameters = getParameters(type, Arrays.asList(paramAnnotations[i]),
                    methodParameters[i], pathParamNames);

            for (Parameter parameter : parameters) {

                operation.parameter(parameter);
            }
        }
    }

    if (operation.getResponses() == null) {
        Response response = new Response().description(SUCCESSFUL_OPERATION);

        operation.response(200, response);
    }

    processOperationDecorator(operation, method);

    return operation;
}

From source file:org.apache.openjpa.meta.MetaDataRepository.java

/**
 * Return true if the given class is the least-derived persistent implementor of the given
 * interface, false otherwise./*from  w ww . ja  va 2 s .  co m*/
 */
private boolean isLeastDerivedImpl(Class<?> inter, Class<?> cls) {
    Class<?> parent = PCRegistry.getPersistentSuperclass(cls);
    while (parent != null) {
        if (Arrays.asList(parent.getInterfaces()).contains(inter))
            return false;
        parent = PCRegistry.getPersistentSuperclass(parent);
    }
    return true;
}

From source file:org.eclipse.wb.internal.core.utils.reflect.ReflectionUtils.java

/**
 * Appends components for {@link PropertyDescriptor}'s of given {@link Class}, its super class and
 * implemented interfaces./*ww  w .  ja va2s .  c  om*/
 */
private static void appendPropertyComponents(Class<?> currentClass, Set<String> newPropertyNames,
        Map<String, Method> propertyToGetter, Map<String, Method> propertyToSetter) {
    for (Method method : currentClass.getDeclaredMethods()) {
        int methodModifiers = method.getModifiers();
        boolean isPublic = Modifier.isPublic(methodModifiers);
        boolean isProtected = Modifier.isProtected(methodModifiers);
        boolean isStatic = Modifier.isStatic(methodModifiers);
        if (method.isBridge()) {
            continue;
        }
        if (!isStatic && (isPublic || isProtected)) {
            method.setAccessible(true);
            String methodName = method.getName();
            if (methodName.startsWith("set") && method.getParameterTypes().length == 1) {
                String propertyName = getQualifiedPropertyName(method);
                if (!propertyToSetter.containsKey(propertyName)) {
                    newPropertyNames.add(propertyName);
                    propertyToSetter.put(propertyName, method);
                }
            }
            if (method.getParameterTypes().length == 0) {
                if (methodName.startsWith("get")) {
                    String propertyName = getQualifiedPropertyName(method);
                    if (!propertyToGetter.containsKey(propertyName)) {
                        newPropertyNames.add(propertyName);
                        propertyToGetter.put(propertyName, method);
                    }
                }
                if (methodName.startsWith("is")) {
                    String propertyName = getQualifiedPropertyName(method);
                    if (!propertyToGetter.containsKey(propertyName)) {
                        newPropertyNames.add(propertyName);
                        propertyToGetter.put(propertyName, method);
                    }
                }
            }
        }
    }
    // process interfaces
    for (Class<?> interfaceClass : currentClass.getInterfaces()) {
        appendPropertyComponents(interfaceClass, newPropertyNames, propertyToGetter, propertyToSetter);
    }
    // process super Class
    if (currentClass.getSuperclass() != null) {
        appendPropertyComponents(currentClass.getSuperclass(), newPropertyNames, propertyToGetter,
                propertyToSetter);
    }
}

From source file:helma.framework.core.Application.java

/**
 * Get the name of the prototype to be used for this object. This will
 * determine which scripts, actions and skins can be called on it
 * within the Helma scripting and rendering framework.
 *///from  ww w .ja v a2  s . co  m
public String getPrototypeName(Object obj) {
    if (obj == null) {
        return "global";
    } else if (obj instanceof IPathElement) {
        // check if e implements the IPathElement interface
        return ((IPathElement) obj).getPrototype();
    }

    // How class name to prototype name lookup works:
    // If an object is not found by its direct class name, a cache entry is added
    // for the class name. For negative result, the string "(unmapped)" is used
    // as cache value.
    //
    // Caching is done directly in classProperties, as ResourceProperties have
    // the nice effect of being purged when the underlying resource is updated,
    // so cache invalidation happens implicitely.

    Class clazz = obj.getClass();
    String className = clazz.getName();
    String protoName = classMapping.getProperty(className);
    // fast path: direct hit, either positive or negative
    if (protoName != null) {
        return protoName == CLASS_NOT_MAPPED ? null : protoName;
    }

    // walk down superclass path. We already checked the actual class,
    // and we know that java.lang.Object does not implement any interfaces,
    // and the code is streamlined a bit to take advantage of this.
    while (clazz != Object.class) {
        // check interfaces
        Class[] classes = clazz.getInterfaces();
        for (int i = 0; i < classes.length; i++) {
            protoName = classMapping.getProperty(classes[i].getName());
            if (protoName != null) {
                // cache the class name for the object so we run faster next time
                classMapping.setProperty(className, protoName);
                return protoName;
            }
        }
        clazz = clazz.getSuperclass();
        protoName = classMapping.getProperty(clazz.getName());
        if (protoName != null) {
            // cache the class name for the object so we run faster next time
            classMapping.setProperty(className, protoName);
            return protoName == CLASS_NOT_MAPPED ? null : protoName;
        }
    }
    // not mapped - cache negative result
    classMapping.setProperty(className, CLASS_NOT_MAPPED);
    return null;
}

From source file:org.apache.myfaces.ov2021.application.ApplicationImpl.java

@SuppressWarnings("unchecked")
private Converter internalCreateConverter(final Class<?> targetClass) {
    // Locate a Converter registered for the target class itself.
    Object converterClassOrClassName = _converterTargetClassToConverterClassMap.get(targetClass);

    // Locate a Converter registered for interfaces that are
    // implemented by the target class (directly or indirectly).
    // Skip if class is String, for performance reasons 
    // (save 3 additional lookups over a concurrent map per request). 
    if (converterClassOrClassName == null && !String.class.equals(targetClass)) {
        final Class<?> interfaces[] = targetClass.getInterfaces();
        if (interfaces != null) {
            for (int i = 0, len = interfaces.length; i < len; i++) {
                // search all superinterfaces for a matching converter,
                // create it
                final Converter converter = internalCreateConverter(interfaces[i]);
                if (converter != null) {
                    return converter;
                }//from w  ww. j a  va 2s.co  m
            }
        }
    }

    // Get EnumConverter for enum classes with no special converter, check
    // here as recursive call with java.lang.Enum will not work
    if (converterClassOrClassName == null && targetClass.isEnum()) {
        converterClassOrClassName = _converterTargetClassToConverterClassMap.get(Enum.class);
    }

    if (converterClassOrClassName != null) {
        try {
            Class<? extends Converter> converterClass = null;
            if (converterClassOrClassName instanceof Class<?>) {
                converterClass = (Class<? extends Converter>) converterClassOrClassName;
            } else if (converterClassOrClassName instanceof String) {
                converterClass = ClassUtils.simpleClassForName((String) converterClassOrClassName);
                _converterTargetClassToConverterClassMap.put(targetClass, converterClass);
            } else {
                //object stored in the map for this id is an invalid type.  remove it and return null
                _converterTargetClassToConverterClassMap.remove(targetClass);
            }

            Converter converter = null;

            // check cached constructor information
            if (!_noArgConstructorConverterClasses.contains(converterClass)) {
                // the converter class either supports the one-arg constructor
                // or has never been processed before
                try {
                    // look for a constructor that takes a single Class object
                    // See JSF 1.2 javadoc for Converter
                    Constructor<? extends Converter> constructor = converterClass
                            .getConstructor(new Class[] { Class.class });

                    converter = constructor.newInstance(new Object[] { targetClass });
                } catch (Exception e) {
                    // the constructor does not exist
                    // add the class to the no-arg constructor classes cache
                    _noArgConstructorConverterClasses.add(converterClass);

                    // use no-arg constructor
                    converter = converterClass.newInstance();
                }
            } else {
                // use no-arg constructor
                converter = converterClass.newInstance();
            }

            setConverterProperties(converterClass, converter);

            return converter;
        } catch (Exception e) {
            log.log(Level.SEVERE, "Could not instantiate converter " + converterClassOrClassName.toString(), e);
            throw new FacesException("Could not instantiate converter: " + converterClassOrClassName.toString(),
                    e);
        }
    }

    // locate converter for primitive types
    if (targetClass == Long.TYPE) {
        return internalCreateConverter(Long.class);
    } else if (targetClass == Boolean.TYPE) {
        return internalCreateConverter(Boolean.class);
    } else if (targetClass == Double.TYPE) {
        return internalCreateConverter(Double.class);
    } else if (targetClass == Byte.TYPE) {
        return internalCreateConverter(Byte.class);
    } else if (targetClass == Short.TYPE) {
        return internalCreateConverter(Short.class);
    } else if (targetClass == Integer.TYPE) {
        return internalCreateConverter(Integer.class);
    } else if (targetClass == Float.TYPE) {
        return internalCreateConverter(Float.class);
    } else if (targetClass == Character.TYPE) {
        return internalCreateConverter(Character.class);
    }

    // Locate a Converter registered for the superclass (if any) of the
    // target class,
    // recursively working up the inheritance hierarchy.
    Class<?> superClazz = targetClass.getSuperclass();

    return superClazz != null ? internalCreateConverter(superClazz) : null;

}

From source file:org.apache.myfaces.application.ApplicationImpl.java

@SuppressWarnings("unchecked")
private Converter internalCreateConverter(final Class<?> targetClass) {
    // Locate a Converter registered for the target class itself.
    Object converterClassOrClassName = _converterTargetClassToConverterClassMap.get(targetClass);

    // Locate a Converter registered for interfaces that are
    // implemented by the target class (directly or indirectly).
    // Skip if class is String, for performance reasons 
    // (save 3 additional lookups over a concurrent map per request). 
    if (converterClassOrClassName == null && !String.class.equals(targetClass)) {
        final Class<?> interfaces[] = targetClass.getInterfaces();
        if (interfaces != null) {
            for (int i = 0, len = interfaces.length; i < len; i++) {
                // search all superinterfaces for a matching converter,
                // create it
                final Converter converter = internalCreateConverter(interfaces[i]);
                if (converter != null) {
                    return converter;
                }//from   w  w  w . jav  a2s.  com
            }
        }
    }

    // Get EnumConverter for enum classes with no special converter, check
    // here as recursive call with java.lang.Enum will not work
    if (converterClassOrClassName == null && targetClass.isEnum()) {
        converterClassOrClassName = _converterTargetClassToConverterClassMap.get(Enum.class);
    }

    if (converterClassOrClassName != null) {
        try {
            Class<? extends Converter> converterClass = null;
            if (converterClassOrClassName instanceof Class<?>) {
                converterClass = (Class<? extends Converter>) converterClassOrClassName;
            } else if (converterClassOrClassName instanceof String) {
                converterClass = ClassUtils.simpleClassForName((String) converterClassOrClassName);
                _converterTargetClassToConverterClassMap.put(targetClass, converterClass);
            } else {
                //object stored in the map for this id is an invalid type.  remove it and return null
                _converterTargetClassToConverterClassMap.remove(targetClass);
            }

            Converter converter = null;

            // check cached constructor information
            if (!_noArgConstructorConverterClasses.contains(converterClass)) {
                // the converter class either supports the one-arg constructor
                // or has never been processed before
                try {
                    // look for a constructor that takes a single Class object
                    // See JSF 1.2 javadoc for Converter
                    Constructor<? extends Converter> constructor = converterClass
                            .getConstructor(new Class[] { Class.class });

                    converter = constructor.newInstance(new Object[] { targetClass });
                } catch (Exception e) {
                    // the constructor does not exist
                    // add the class to the no-arg constructor classes cache
                    _noArgConstructorConverterClasses.add(converterClass);

                    // use no-arg constructor
                    converter = createConverterInstance(converterClass);
                }
            } else {
                // use no-arg constructor
                converter = createConverterInstance(converterClass);
            }

            setConverterProperties(converterClass, converter);

            return converter;
        } catch (Exception e) {
            log.log(Level.SEVERE, "Could not instantiate converter " + converterClassOrClassName.toString(), e);
            throw new FacesException("Could not instantiate converter: " + converterClassOrClassName.toString(),
                    e);
        }
    }

    // locate converter for primitive types
    if (targetClass == Long.TYPE) {
        return internalCreateConverter(Long.class);
    } else if (targetClass == Boolean.TYPE) {
        return internalCreateConverter(Boolean.class);
    } else if (targetClass == Double.TYPE) {
        return internalCreateConverter(Double.class);
    } else if (targetClass == Byte.TYPE) {
        return internalCreateConverter(Byte.class);
    } else if (targetClass == Short.TYPE) {
        return internalCreateConverter(Short.class);
    } else if (targetClass == Integer.TYPE) {
        return internalCreateConverter(Integer.class);
    } else if (targetClass == Float.TYPE) {
        return internalCreateConverter(Float.class);
    } else if (targetClass == Character.TYPE) {
        return internalCreateConverter(Character.class);
    }

    // Locate a Converter registered for the superclass (if any) of the
    // target class,
    // recursively working up the inheritance hierarchy.
    Class<?> superClazz = targetClass.getSuperclass();

    return superClazz != null ? internalCreateConverter(superClazz) : null;

}

From source file:org.apache.openjpa.meta.MetaDataRepository.java

/**
 * Update the list of implementations of base classes and interfaces.
 *//*from   www . j a  v  a  2s . c  om*/
private void updateImpls(Class<?> cls, Class<?> leastDerived, Class<?> check) {
    // allow users to query on common non-pc superclasses
    Class<?> sup = check.getSuperclass();
    if (leastDerived == cls && sup != null && sup != Object.class) {
        addToCollection(_impls, sup, cls, false);
        updateImpls(cls, leastDerived, sup);
    }

    // allow users to query on any implemented interfaces unless defaults
    // say the user must implement persistent interfaces explicitly in meta
    if (!_factory.getDefaults().isDeclaredInterfacePersistent())
        return;
    Class<?>[] ints = check.getInterfaces();
    for (int i = 0; i < ints.length; i++) {
        // don't map java-standard interfaces
        if (ints[i].getName().startsWith("java."))
            continue;

        // only map least-derived interface implementors
        if (leastDerived == cls || isLeastDerivedImpl(ints[i], cls)) {
            addToCollection(_impls, ints[i], cls, false);
            updateImpls(cls, leastDerived, ints[i]);
        }
    }
}

From source file:com.openddal.test.BaseTestCase.java

/**
 * Verify the next method call on the object will throw an exception.
 *
 * @param <T> the class of the object
 * @param verifier the result verifier to call
 * @param obj the object to wrap/*  w w w  .  j  a v  a 2 s  .c  o  m*/
 * @return a proxy for the object
 */
@SuppressWarnings("unchecked")
protected <T> T assertThrows(final ResultVerifier verifier, final T obj) {
    Class<?> c = obj.getClass();
    InvocationHandler ih = new InvocationHandler() {
        private Exception called = new Exception("No method called");

        @Override
        protected void finalize() {
            if (called != null) {
                called.printStackTrace(System.err);
            }
        }

        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Exception {
            try {
                called = null;
                Object ret = method.invoke(obj, args);
                verifier.verify(ret, null, method, args);
                return ret;
            } catch (InvocationTargetException e) {
                verifier.verify(null, e.getTargetException(), method, args);
                Class<?> retClass = method.getReturnType();
                if (!retClass.isPrimitive()) {
                    return null;
                }
                if (retClass == boolean.class) {
                    return false;
                } else if (retClass == byte.class) {
                    return (byte) 0;
                } else if (retClass == char.class) {
                    return (char) 0;
                } else if (retClass == short.class) {
                    return (short) 0;
                } else if (retClass == int.class) {
                    return 0;
                } else if (retClass == long.class) {
                    return 0L;
                } else if (retClass == float.class) {
                    return 0F;
                } else if (retClass == double.class) {
                    return 0D;
                }
                return null;
            }
        }
    };
    if (!ProxyCodeGenerator.isGenerated(c)) {
        Class<?>[] interfaces = c.getInterfaces();
        if (Modifier.isFinal(c.getModifiers()) || (interfaces.length > 0 && getClass() != c)) {
            // interface class proxies
            if (interfaces.length == 0) {
                throw new RuntimeException("Can not create a proxy for the class " + c.getSimpleName()
                        + " because it doesn't implement any interfaces and is final");
            }
            return (T) Proxy.newProxyInstance(c.getClassLoader(), interfaces, ih);
        }
    }
    try {
        Class<?> pc = ProxyCodeGenerator.getClassProxy(c);
        Constructor<?> cons = pc.getConstructor(InvocationHandler.class);
        return (T) cons.newInstance(ih);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}