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:com.strandls.alchemy.rest.client.stubgenerator.ServiceStubGenerator.java

/**
 * Add a rest method to the parent class.
 *
 * @param jCodeModel/*from ww  w . ja  va2  s.c  om*/
 *            the code model.
 * @param jParentClass
 *            the parent class.
 * @param method
 *            the method.
 * @param methodMetaData
 *            the method metadata.
 */
private void addMethod(final JCodeModel jCodeModel, final JDefinedClass jParentClass, final Method method,
        final RestMethodMetadata methodMetaData) {
    final String mehtodName = method.getName();

    final JType result = typeToJType(method.getReturnType(), method.getGenericReturnType(), jCodeModel);

    final JMethod jMethod = jParentClass.method(JMod.PUBLIC, result, mehtodName);

    @SuppressWarnings("unchecked")
    final Class<? extends Throwable>[] exceptionTypes = (Class<? extends Throwable>[]) method
            .getExceptionTypes();

    for (final Class<? extends Throwable> exceptionCType : exceptionTypes) {
        jMethod._throws(exceptionCType);
    }

    addSingleValueAnnotation(jMethod, Path.class, ANNOTATION_VALUE_PARAM_NAME, methodMetaData.getPath());

    addListAnnotation(jMethod, Produces.class, ANNOTATION_VALUE_PARAM_NAME, methodMetaData.getProduced());
    addListAnnotation(jMethod, Consumes.class, ANNOTATION_VALUE_PARAM_NAME, methodMetaData.getConsumed());

    final String httpMethod = methodMetaData.getHttpMethod();
    Class<? extends Annotation> httpMethodAnnotation = null;
    if (HttpMethod.GET.equals(httpMethod)) {
        httpMethodAnnotation = GET.class;
    } else if (HttpMethod.PUT.equals(httpMethod)) {
        httpMethodAnnotation = PUT.class;
    } else if (HttpMethod.POST.equals(httpMethod)) {
        httpMethodAnnotation = POST.class;
    } else if (HttpMethod.DELETE.equals(httpMethod)) {
        httpMethodAnnotation = DELETE.class;
    }

    addAnnotation(jMethod, httpMethodAnnotation);

    final Annotation[][] parameterAnnotations = methodMetaData.getParameterAnnotations();

    final Type[] argumentTypes = method.getGenericParameterTypes();
    final Class<?>[] argumentClasses = method.getParameterTypes();
    for (int i = 0; i < argumentTypes.length; i++) {
        final JType jType = typeToJType(argumentClasses[i], argumentTypes[i], jCodeModel);
        // we have lost the actual names, use generic arg names
        final String name = "arg" + i;
        final JVar param = jMethod.param(jType, name);
        if (parameterAnnotations.length > i) {
            for (final Annotation annotation : parameterAnnotations[i]) {
                final JAnnotationUse jAnnotation = param.annotate(annotation.annotationType());
                final String value = getValue(annotation);
                if (value != null) {
                    jAnnotation.param(ANNOTATION_VALUE_PARAM_NAME, value);
                }
            }
        }
    }
}

From source file:com.appleframework.core.utils.ClassUtility.java

/** ??method?? */
public static String getSimpleMethodSignature(Method method, boolean withModifiers, boolean withReturnType,
        boolean withClassName, boolean withExceptionType) {
    if (method == null) {
        return null;
    }// ww  w .ja v  a  2 s.c om

    StringBuilder buf = new StringBuilder();

    if (withModifiers) {
        buf.append(Modifier.toString(method.getModifiers())).append(' ');
    }

    if (withReturnType) {
        buf.append(getSimpleClassName(method.getReturnType())).append(' ');
    }

    if (withClassName) {
        buf.append(getSimpleClassName(method.getDeclaringClass())).append('.');
    }

    buf.append(method.getName()).append('(');

    Class<?>[] paramTypes = method.getParameterTypes();

    for (int i = 0; i < paramTypes.length; i++) {
        Class<?> paramType = paramTypes[i];

        buf.append(getSimpleClassName(paramType));

        if (i < paramTypes.length - 1) {
            buf.append(", ");
        }
    }

    buf.append(')');

    if (withExceptionType) {
        Class<?>[] exceptionTypes = method.getExceptionTypes();

        if (!isEmptyArray(exceptionTypes)) {
            buf.append(" throws ");

            for (int i = 0; i < exceptionTypes.length; i++) {
                Class<?> exceptionType = exceptionTypes[i];

                buf.append(getSimpleClassName(exceptionType));

                if (i < exceptionTypes.length - 1) {
                    buf.append(", ");
                }
            }
        }
    }

    return buf.toString();
}

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

@Override
public List<ValidationMessage> validate(Method readMethod, String property, Object value, ValidationMode mode)
        throws RuleValidationException {
    LessThan greaterThanAnnotation = readMethod.getAnnotation(LessThan.class);
    List<ValidationMessage> messages = null;
    if (greaterThanAnnotation != null) {
        messages = new ArrayList<ValidationMessage>();
        Class<?> returnType = readMethod.getReturnType();
        String parameterName = StringUtils.isBlank(greaterThanAnnotation.parameterName()) ? property
                : greaterThanAnnotation.parameterName();
        if (value != null) {
            if (returnType.getSuperclass() == Number.class || returnType.isPrimitive()) {
                boolean checkEquality = greaterThanAnnotation.checkEquality();
                Number val = null;
                if (returnType == Float.class || returnType == float.class) {
                    Float f = (Float) value;
                    if (checkEquality && f > greaterThanAnnotation.floatVal()
                            || !checkEquality && f >= greaterThanAnnotation.floatVal()) {
                        val = greaterThanAnnotation.floatVal();
                    }/*from www  . ja va 2 s  .  co m*/
                } else if (returnType == Double.class || returnType == double.class) {
                    Double d = (Double) value;
                    if (checkEquality && d > greaterThanAnnotation.doubleVal()
                            || !checkEquality && d >= greaterThanAnnotation.doubleVal()) {
                        val = greaterThanAnnotation.doubleVal();
                    }
                } else {
                    Long longValue = ((Number) value).longValue();
                    Long rangeValue = ((Integer) greaterThanAnnotation.intVal()).longValue();
                    if (checkEquality && longValue > rangeValue || !checkEquality && longValue >= rangeValue) {
                        val = greaterThanAnnotation.intVal();
                    }
                }
                if (val != null) {
                    messages.add(new ValidationMessage(property,
                            checkEquality ? greaterThanAnnotation.equalityMsgKey()
                                    : greaterThanAnnotation.msgKey(),
                            parameterName, val));
                }
            }
        }
    }
    return messages;
}

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

@Test(expected = NoSuchMethodException.class)
public void additionalPropertiesBuilderAbsentIfNotConfigured()
        throws SecurityException, NoSuchMethodException, ClassNotFoundException {

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

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

    // builder with these types should not exist:
    Method builderMethod = classWithNoAdditionalProperties.getMethod("withAdditionalProperty", String.class,
            propertyValueType);/* w w  w .j ava  2 s . co  m*/
    assertThat("the builder method returns this type", builderMethod.getReturnType(),
            typeEqualTo(classWithNoAdditionalProperties));

    fail("additional properties builder found when not requested");
}

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

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

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

    Class<?> classWithNoAdditionalProperties = resultsClassLoader
            .loadClass("com.example.AdditionalPropertiesArraysOfStrings");
    Method getter = classWithNoAdditionalProperties.getMethod("getAdditionalProperties");

    ParameterizedType listType = (ParameterizedType) ((ParameterizedType) getter.getGenericReturnType())
            .getActualTypeArguments()[1];
    assertThat(listType.getActualTypeArguments()[0], is(equalTo((Type) String.class)));

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

    // builder with these types should exist:
    Method builderMethod = classWithNoAdditionalProperties.getMethod("withAdditionalProperty", String.class,
            List.class);
    assertThat("the builder method returns this type", builderMethod.getReturnType(),
            typeEqualTo(classWithNoAdditionalProperties));

}

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

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

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

    Class<?> classWithNoAdditionalProperties = resultsClassLoader
            .loadClass("com.example.AdditionalPropertiesString");
    Method getter = classWithNoAdditionalProperties.getMethod("getAdditionalProperties");

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

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

    // builder with these types should exist:
    Method builderMethod = classWithNoAdditionalProperties.getMethod("withAdditionalProperty", String.class,
            String.class);
    assertThat("the builder method returns this type", builderMethod.getReturnType(),
            typeEqualTo(classWithNoAdditionalProperties));

}

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

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

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

    Class<?> classWithNoAdditionalProperties = resultsClassLoader
            .loadClass("com.example.AdditionalPropertiesPrimitiveBoolean");
    Method getter = classWithNoAdditionalProperties.getMethod("getAdditionalProperties");

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

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

    // builder with these types should exist:
    Method builderMethod = classWithNoAdditionalProperties.getMethod("withAdditionalProperty", String.class,
            boolean.class);
    assertThat("the builder method returns this type", builderMethod.getReturnType(),
            typeEqualTo(classWithNoAdditionalProperties));

}

From source file:com.mnxfst.testing.handler.exec.PTestPlanExecutionContext.java

/**
 * Extracts the  {@link Method method representations} for the given path of getter methods 
 * @param varType// w  w  w  .j  a  va 2  s.  co m
 * @param getterMethodNames
 * @param result
 * @throws ContextVariableEvaluationFailedException
 */
protected void extractGetterMethods(Class<?> varType, String[] getterMethodNames, List<Method> result)
        throws ContextVariableEvaluationFailedException {

    if (varType != null && getterMethodNames != null && getterMethodNames.length > 0) {

        String nextGetter = getterMethodNames[0];
        try {
            Method getterMethod = varType.getMethod(nextGetter);
            result.add(getterMethod);
            extractGetterMethods(getterMethod.getReturnType(),
                    (String[]) ArrayUtils.subarray(getterMethodNames, 1, getterMethodNames.length), result);
        } catch (NoSuchMethodException e) {
            throw new ContextVariableEvaluationFailedException(
                    "No such getter '" + nextGetter + "' for class " + varType.getName());
        }

    }

}

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

@Override
public List<Constraint> generate(Method readMethod, String property, Map<String, String> params) {
    List<Constraint> constraints = null;
    Annotation annotation = readMethod.getAnnotation(LessThan.class);
    if (annotation != null) {
        LessThan lessThan = (LessThan) annotation;
        Constraint constraint = new Constraint(lessThan.annotationType().getSimpleName());
        Class<?> returnType = readMethod.getReturnType();
        if (returnType.getSuperclass() == Number.class || returnType.isPrimitive()) {
            List<RuleParameter> ruleParameters = new ArrayList<RuleParameter>();

            boolean checkEquality = lessThan.checkEquality();
            RuleParameter checkEqualityParam = new RuleParameter("checkEquality", checkEquality);
            ruleParameters.add(checkEqualityParam);

            String errorMessage;/*from   ww w  .j  a  v a2  s . c om*/
            RuleParameter valueParam;
            String messageKey = checkEquality ? lessThan.equalityMsgKey() : lessThan.msgKey();
            if (returnType == Float.class || returnType == float.class) {
                errorMessage = MessageResolver.messageFormatting(messageKey, Locale.ENGLISH, property,
                        lessThan.floatVal());
                valueParam = new RuleParameter("lessThanValue", lessThan.floatVal());
            } else if (returnType == Double.class || returnType == double.class) {
                errorMessage = MessageResolver.messageFormatting(messageKey, Locale.ENGLISH, property,
                        lessThan.doubleVal());
                valueParam = new RuleParameter("lessThanValue", lessThan.doubleVal());
            } else {
                errorMessage = MessageResolver.messageFormatting(messageKey, Locale.ENGLISH, property,
                        lessThan.intVal());
                valueParam = new RuleParameter("lessThanValue", lessThan.intVal());
            }
            constraint.setErrorMessage(errorMessage);
            ruleParameters.add(valueParam);

            constraint.setParams(ruleParameters);
            constraints = new ArrayList<Constraint>();
            constraints.add(constraint);
        }
    }
    return constraints;
}

From source file:net.mojodna.sprout.Sprout.java

public final void setBeanFactory(final BeanFactory factory) throws BeansException {
    if (!factory.isSingleton(beanName)) {
        log.warn(getClass().getName() + " must be defined with singleton=\"true\" in order to self-register.");
        return;//from ww w  . j av a 2  s. c  o  m
    }

    final String pkgName = getClass().getPackage().getName();
    final String path = pkgName.substring(pkgName.indexOf(PACKAGE_DELIMITER) + PACKAGE_DELIMITER.length())
            .replace('.', '/') + "/";

    if (factory instanceof AbstractBeanFactory) {
        final AbstractBeanFactory dlbf = (AbstractBeanFactory) factory;

        final Collection<Method> methods = SproutUtils.getDeclaredMethods(getClass(), Sprout.class);

        // register beans for each url
        log.debug("Registering paths...");
        for (final Iterator<Method> i = methods.iterator(); i.hasNext();) {
            final Method method = i.next();
            String name = method.getName();
            if (Modifier.isPublic(method.getModifiers())
                    && method.getReturnType().equals(ActionForward.class)) {
                if (name.equals("publick"))
                    name = "public";
                final String url = path + name.replaceAll("([A-Z])", "_$1").toLowerCase();
                log.debug(url);
                if (!ArrayUtils.contains(dlbf.getAliases(beanName), url))
                    dlbf.registerAlias(beanName, url);
            }
        }
    } else {
        log.warn("Unable to self-register; factory bean was of an unsupported type.");
        throw new BeanNotOfRequiredTypeException(beanName, AbstractBeanFactory.class, factory.getClass());
    }
}