Example usage for java.lang.reflect Method getReturnType

List of usage examples for java.lang.reflect Method getReturnType

Introduction

In this page you can find the example usage for java.lang.reflect Method getReturnType.

Prototype

public Class<?> getReturnType() 

Source Link

Document

Returns a Class object that represents the formal return type of the method represented by this Method object.

Usage

From source file:org.jsonschema2pojo.integration.AdditionalPropertiesIT.java

@Test
public void additionalPropertiesOfObjectTypeCreatesNewClassForPropertyValues()
        throws SecurityException, NoSuchMethodException, ClassNotFoundException {

    ClassLoader resultsClassLoader = schemaRule.generateAndCompile(
            "/schema/additionalProperties/additionalPropertiesObject.json", "com.example",
            config("generateBuilders", true));

    Class<?> classWithNoAdditionalProperties = resultsClassLoader
            .loadClass("com.example.AdditionalPropertiesObject");
    Class<?> propertyValueType = resultsClassLoader.loadClass("com.example.AdditionalPropertiesObjectProperty");

    Method getter = classWithNoAdditionalProperties.getMethod("getAdditionalProperties");

    assertThat(((ParameterizedType) getter.getGenericReturnType()).getActualTypeArguments()[1],
            is(equalTo((Type) propertyValueType)));

    // setter with these types should exist:
    classWithNoAdditionalProperties.getMethod("setAdditionalProperty", String.class, propertyValueType);

    // builder with these types should exist:
    Method builderMethod = classWithNoAdditionalProperties.getMethod("withAdditionalProperty", String.class,
            propertyValueType);/*ww  w  .j a  v a2s  .  c  o m*/
    assertThat("the builder method returns this type", builderMethod.getReturnType(),
            typeEqualTo(classWithNoAdditionalProperties));

}

From source file:com.cloudera.impala.catalog.CatalogServiceCatalog.java

/**
 * Returns a list of Impala Functions, one per compatible "evaluate" method in the UDF
 * class referred to by the given Java function. This method copies the UDF Jar
 * referenced by "function" to a temporary file in "LOCAL_LIBRARY_PATH" and loads it
 * into the jvm. Then we scan all the methods in the class using reflection and extract
 * those methods and create corresponding Impala functions. Currently Impala supports
 * only "JAR" files for symbols and also a single Jar containing all the dependent
 * classes rather than a set of Jar files.
 *//*from  ww  w .  ja  v a 2  s .  com*/
public static List<Function> extractFunctions(String db, org.apache.hadoop.hive.metastore.api.Function function)
        throws ImpalaRuntimeException {
    List<Function> result = Lists.newArrayList();
    List<String> addedSignatures = Lists.newArrayList();
    boolean compatible = true;
    StringBuilder warnMessage = new StringBuilder();
    if (function.getFunctionType() != FunctionType.JAVA) {
        compatible = false;
        warnMessage.append("Function type: " + function.getFunctionType().name() + " is not supported. Only "
                + FunctionType.JAVA.name() + " functions " + "are supported.");
    }
    if (function.getResourceUrisSize() != 1) {
        compatible = false;
        List<String> resourceUris = Lists.newArrayList();
        for (ResourceUri resource : function.getResourceUris()) {
            resourceUris.add(resource.getUri());
        }
        warnMessage.append("Impala does not support multiple Jars for dependencies." + "("
                + Joiner.on(",").join(resourceUris) + ") ");
    }
    if (function.getResourceUris().get(0).getResourceType() != ResourceType.JAR) {
        compatible = false;
        warnMessage.append("Function binary type: " + function.getResourceUris().get(0).getResourceType().name()
                + " is not supported. Only " + ResourceType.JAR.name() + " type is supported.");
    }
    if (!compatible) {
        LOG.warn("Skipping load of incompatible Java function: " + function.getFunctionName() + ". "
                + warnMessage.toString());
        return result;
    }
    String jarUri = function.getResourceUris().get(0).getUri();
    Class<?> udfClass = null;
    try {
        Path localJarPath = new Path(LOCAL_LIBRARY_PATH, UUID.randomUUID().toString() + ".jar");
        if (!FileSystemUtil.copyToLocal(new Path(jarUri), localJarPath)) {
            String errorMsg = "Error loading Java function: " + db + "." + function.getFunctionName()
                    + ". Couldn't copy " + jarUri + " to local path: " + localJarPath.toString();
            LOG.error(errorMsg);
            throw new ImpalaRuntimeException(errorMsg);
        }
        URL[] classLoaderUrls = new URL[] { new URL(localJarPath.toString()) };
        URLClassLoader urlClassLoader = new URLClassLoader(classLoaderUrls);
        udfClass = urlClassLoader.loadClass(function.getClassName());
        // Check if the class is of UDF type. Currently we don't support other functions
        // TODO: Remove this once we support Java UDAF/UDTF
        if (FunctionUtils.getUDFClassType(udfClass) != FunctionUtils.UDFClassType.UDF) {
            LOG.warn("Ignoring load of incompatible Java function: " + function.getFunctionName() + " as "
                    + FunctionUtils.getUDFClassType(udfClass)
                    + " is not a supported type. Only UDFs are supported");
            return result;
        }
        // Load each method in the UDF class and create the corresponding Impala Function
        // object.
        for (Method m : udfClass.getMethods()) {
            if (!m.getName().equals("evaluate"))
                continue;
            Function fn = ScalarFunction.fromHiveFunction(db, function.getFunctionName(),
                    function.getClassName(), m.getParameterTypes(), m.getReturnType(), jarUri);
            if (fn == null) {
                LOG.warn("Ignoring incompatible method: " + m.toString() + " during load of " + "Hive UDF:"
                        + function.getFunctionName() + " from " + udfClass);
                continue;
            }
            if (!addedSignatures.contains(fn.signatureString())) {
                result.add(fn);
                addedSignatures.add(fn.signatureString());
            }
        }
    } catch (ClassNotFoundException c) {
        String errorMsg = "Error loading Java function: " + db + "." + function.getFunctionName()
                + ". Symbol class " + udfClass + "not found in Jar: " + jarUri;
        LOG.error(errorMsg);
        throw new ImpalaRuntimeException(errorMsg, c);
    } catch (Exception e) {
        LOG.error("Skipping function load: " + function.getFunctionName(), e);
        throw new ImpalaRuntimeException("Error extracting functions", e);
    }
    return result;
}

From source file:Main.java

public static void dumpMethod(final Method method) {
    final StringBuilder builder = new StringBuilder();
    builder.append("------------------------------\n");
    builder.append("MethodName: ").append(method.getName()).append("\n");
    builder.append("ParameterTypes:{");
    for (Class<?> cls : method.getParameterTypes()) {
        builder.append(cls.getName()).append(", ");
    }//  w  ww  . ja  va 2s . co m
    builder.append("}\n");
    builder.append("GenericParameterTypes:{");
    for (Type cls : method.getGenericParameterTypes()) {
        builder.append(cls.getClass()).append(", ");
    }
    builder.append("}\n");
    builder.append("TypeParameters:{");
    for (TypeVariable<Method> cls : method.getTypeParameters()) {
        builder.append(cls.getName()).append(", ");
    }
    builder.append("}\n");
    builder.append("DeclaredAnnotations:{");
    for (Annotation cls : method.getDeclaredAnnotations()) {
        builder.append(cls).append(", ");
    }
    builder.append("}\n");
    builder.append("Annotations:{");
    for (Annotation cls : method.getAnnotations()) {
        builder.append(cls).append(", ");
    }
    builder.append("}\n");
    builder.append("ExceptionTypes:{");
    for (Class<?> cls : method.getExceptionTypes()) {
        builder.append(cls.getName()).append(", ");
        ;
    }
    builder.append("}\n");
    builder.append("ReturnType: ").append(method.getReturnType());
    builder.append("\nGenericReturnType: ").append(method.getGenericReturnType());
    builder.append("\nDeclaringClass: ").append(method.getDeclaringClass());
    builder.append("\n");

    System.out.println(builder.toString());
}

From source file:com.ms.commons.summer.web.handler.ComponentMethodHandlerAdapter.java

private Method getValidationMethod(ValidationToken validation, Class<?> c) {
    String methodName = null;/*  w  ww . j a  v a2s  .co  m*/
    if (StringUtils.isNotEmpty(validation.methodName())) {
        methodName = validation.methodName();
    } else {
        methodName = validation.type().getMethodName();
    }
    try {
        Method method = c.getMethod(methodName, Map.class, String.class);
        if (method == null) {
            return null;
        }
        Class<?> returnType = method.getReturnType();
        if (!returnType.isAssignableFrom(WebResult.class)) {
            return null;
        }
        return method;
    } catch (SecurityException e) {
    } catch (NoSuchMethodException e) {
    }
    return null;
}

From source file:com.netflix.hystrix.contrib.javanica.aop.aspectj.HystrixCommandAspect.java

@Around("hystrixCommandAnnotationPointcut()")
public Object methodsAnnotatedWithHystrixCommand(final ProceedingJoinPoint joinPoint) throws Throwable {

    Method method = getMethodFromTarget(joinPoint);
    Object obj = joinPoint.getTarget();
    Object[] args = joinPoint.getArgs();
    Validate.notNull(method, "failed to get method from joinPoint: %s", joinPoint);
    HystrixCommand hystrixCommand = method.getAnnotation(HystrixCommand.class);
    HystrixCollapser hystrixCollapser = method.getAnnotation(HystrixCollapser.class);
    ExecutionType executionType = ExecutionType.getExecutionType(method.getReturnType());
    Method cacheKeyMethod = getMethodFromTarget(joinPoint, hystrixCommand.cacheKeyMethod());
    MetaHolder metaHolder = MetaHolder.builder().args(args).method(method).obj(obj)
            .proxyObj(joinPoint.getThis()).cacheKeyMethod(cacheKeyMethod).executionType(executionType)
            .hystrixCommand(hystrixCommand).hystrixCollapser(hystrixCollapser)
            .defaultCommandKey(method.getName()).defaultCollapserKey(method.getName())
            .defaultGroupKey(obj.getClass().getSimpleName()).build();
    HystrixExecutable executable;//from   w ww  .j  a  v a2s .c  o m
    if (hystrixCollapser != null) {
        executable = new CommandCollapser(metaHolder);
    } else {
        executable = GenericHystrixCommandFactory.getInstance().create(metaHolder, null);
    }
    Object result;
    try {
        result = CommandExecutor.execute(executable, executionType);
    } catch (HystrixBadRequestException e) {
        throw e.getCause();
    } catch (Throwable throwable) {
        throw throwable;
    }
    return result;
}

From source file:com.openmeap.web.form.ParameterMapBuilder.java

public void fromParameters(Object obj, Map<String, Object> parameters, String prefix)
        throws ParameterMapBuilderException {

    Class clazz = obj.getClass();
    for (Map.Entry<String, Object> entry : parameters.entrySet()) {

        String formName = entry.getKey().replaceFirst(prefix, "");
        if (entry.getValue() == null || (String.class.isAssignableFrom(entry.getValue().getClass())
                && StringUtils.isBlank((String) entry.getValue()))) {
            continue;
        }//from ww w.  ja  v  a  2s .c o m

        Method getterMethod = methodForFormName(clazz, formName);
        if (getterMethod == null) {
            continue;
        }
        Method setterMethod = PropertyUtils.setterForGetterMethod(getterMethod);
        Constructor constructor = null;

        Class<?> valueClass = null;
        try {
            valueClass = getterMethod.getReturnType();
            constructor = valueClass.getConstructor(valueClass);
        } catch (Exception e) {
            ;//throw new ParameterMapBuilderException(e);
        }

        Object value = null;
        try {
            if (this.useParameterMapUtilsFirstValue) {
                value = ParameterMapUtils.firstValue(formName, (Map) parameters);
            } else {
                value = parameters.get(formName);
            }
            if (value != null) {
                if (constructor != null) {
                    value = constructor.newInstance(value);
                } else {
                    value = PropertyUtils.correctCasting(valueClass, value);
                }
            }
        } catch (Exception e) {
            throw new ParameterMapBuilderException(e);
        }

        try {
            setterMethod.invoke(obj, value);
        } catch (Exception e) {
            throw new ParameterMapBuilderException(e);
        }
    }
}

From source file:net.firejack.platform.core.validation.NotMatchProcessor.java

@Override
public List<ValidationMessage> validate(Method readMethod, String property, Object value, ValidationMode mode)
        throws RuleValidationException {
    List<ValidationMessage> messages = new ArrayList<ValidationMessage>();
    NotMatch notMatchAnnotation = readMethod.getAnnotation(NotMatch.class);
    if (notMatchAnnotation != null && StringUtils.isNotBlank(notMatchAnnotation.expression())) {
        Class<?> returnType = readMethod.getReturnType();
        if (returnType == String.class) {
            Pattern pattern = getCachedPatterns().get(notMatchAnnotation.expression());
            if (pattern == null) {
                try {
                    pattern = Pattern.compile(notMatchAnnotation.expression());
                    getCachedPatterns().put(notMatchAnnotation.expression(), pattern);
                } catch (PatternSyntaxException e) {
                    logger.error(e.getMessage(), e);
                    throw new ImproperValidationArgumentException(
                            "Pattern expression should have correct syntax.");
                }//from w w  w.  j  a va  2  s.  com
            }
            if (value != null) {
                String sValue = (String) value;
                if (StringUtils.isNotBlank(sValue) && pattern.matcher(sValue).matches()) {
                    messages.add(new ValidationMessage(property, notMatchAnnotation.msgKey(),
                            notMatchAnnotation.parameterName()));
                }
            }
        }
    }

    if (notMatchAnnotation != null && !notMatchAnnotation.javaWords()) {
        Class<?> returnType = readMethod.getReturnType();
        if (returnType == String.class && StringUtils.isNotBlank((String) value)) {
            String s = (String) value;
            for (String word : words) {
                if (word.equals(s)) {
                    messages.add(new ValidationMessage(property, notMatchAnnotation.msgKey(), word));
                }
            }
        }
    }

    return messages;
}

From source file:com.hortonworks.streamline.streams.service.UDFCatalogResource.java

private Schema.Type getReturnType(Class<?> clazz, String methodName) {
    try {// w w  w . java2s .  c  o  m
        Method method = findMethod(clazz, methodName);
        if (method != null) {
            return Schema.fromJavaType(method.getReturnType());
        }
    } catch (ParserException ex) {
        LOG.warn("Could not determine return type for {}", clazz);
    }
    return null;
}

From source file:com.medallia.spider.api.StRenderer.java

private Object createInput(Class<?> x, final DynamicInputImpl dynamicInput) {
    return Proxy.newProxyInstance(x.getClassLoader(), new Class<?>[] { x }, new InvocationHandler() {
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            return dynamicInput.getInput(method.getName(), method.getReturnType(), method);
        }//from w  w w  . ja v  a2s .  c  o m
    });
}