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.google.code.ssm.aop.CacheBase.java

protected void verifyReturnTypeIsNoVoid(final Method method, final Class<?> annotationClass) {
    if (method.getReturnType().equals(void.class)) {
        throw new InvalidParameterException(String.format("Annotation [%s] is defined on void method  [%s]",
                annotationClass, method.getName()));
    }/*from  w  w w  . ja  v a2s .c  o  m*/
}

From source file:de.ufinke.cubaja.sql.ObjectFactoryGenerator.java

private void createSetterMap(Class<?> clazz) {

    setterMap = new HashMap<String, SetterEntry>();

    for (Method method : clazz.getMethods()) {

        if (method.getReturnType() == Void.TYPE) {

            String methodName = method.getName();
            SearchEntry searchEntry = searchMap.get(methodName);

            if (searchEntry != null && method.getReturnType() == Void.TYPE) {

                int position = searchEntry.position;
                Class<?>[] parameterTypes = method.getParameterTypes();

                if (parameterTypes.length == 1) {

                    TypeCombination combination = new TypeCombination(searchEntry.sqlType, parameterTypes[0]);
                    ObjectFactoryType type = ObjectFactoryType.getType(combination);

                    if (type != null) {

                        SetterEntry entry = setterMap.get(methodName);

                        if (entry == null || type.getPriority() < entry.type.getPriority()) {
                            setterMap.put(methodName, new SetterEntry(methodName, type, position));
                            searchEntry.setterFound = true;
                        }//from   w  w w .  j  a v  a 2s  .co  m
                    }
                }
            }
        }
    }
}

From source file:de.perdian.commons.i18n.polyglot.PolyglotImpl.java

private PolyglotInvocationInfo createInvocationInfo(Method interfaceMethod, PolyglotKeyGenerator keyGenerator) {
    Class<?> returnType = interfaceMethod.getReturnType();
    if (!returnType.isAssignableFrom(String.class)) {
        throw new IllegalArgumentException("Return type '" + returnType.getName()
                + "' is not compatible to result type '" + String.class.getName() + "'");
    } else {/* w  ww .  j a v  a  2 s . com*/

        PolyglotKey polyglotKey = interfaceMethod.getAnnotation(PolyglotKey.class);
        String interfaceKey = polyglotKey == null ? interfaceMethod.getName() : polyglotKey.value();
        PolyglotDefault polyglotDefault = interfaceMethod.getAnnotation(PolyglotDefault.class);

        PolyglotInvocationInfo invocationInfo = new PolyglotInvocationInfo();
        invocationInfo.setDefaultValue(polyglotDefault == null ? null : polyglotDefault.value());
        invocationInfo.setKey(keyGenerator.generateKey(interfaceKey));
        return invocationInfo;

    }
}

From source file:com.katsu.jpa.dao.JpaDao.java

public boolean isEntity(Method m) {
    return m.getReturnType().isAnnotationPresent(javax.persistence.Entity.class);
}

From source file:com.flipkart.polyguice.dropwiz.DropConfigProvider.java

private String getNameFromMethod(Method method) {
    if (method.getParameterCount() > 0) {
        return null;
    }//  w w w  .j ava  2s.co m
    if (method.getReturnType().equals(Void.TYPE)) {
        return null;
    }

    String mthdName = method.getName();
    if (mthdName.startsWith("get")) {
        if (mthdName.length() <= 3) {
            return null;
        }
        if (method.getReturnType().equals(Boolean.class) || method.getReturnType().equals(Boolean.TYPE)) {
            return null;
        }
        StringBuffer buffer = new StringBuffer(StringUtils.removeStart(mthdName, "get"));
        buffer.setCharAt(0, Character.toLowerCase(buffer.charAt(0)));
        return buffer.toString();
    } else if (!mthdName.startsWith("is")) {
        if (mthdName.length() <= 2) {
            return null;
        }
        if (!method.getReturnType().equals(Boolean.class) && !method.getReturnType().equals(Boolean.TYPE)) {
            return null;
        }
        StringBuffer buffer = new StringBuffer(StringUtils.removeStart(mthdName, "is"));
        buffer.setCharAt(0, Character.toLowerCase(buffer.charAt(0)));
        return buffer.toString();
    }
    return null;
}

From source file:com.jxva.exception.ExceptionUtil.java

/**
 * <p>Finds a <code>Throwable</code> by method name.</p>
 *
 * @param throwable  the exception to examine
 * @param methodName  the name of the method to find and invoke
 * @return the wrapped exception, or <code>null</code> if not found
 *///from   w w w . j  a v a2 s  .c om
private static Throwable getCauseUsingMethodName(Throwable throwable, String methodName) {
    Method method = null;
    try {
        method = throwable.getClass().getMethod(methodName);
    } catch (NoSuchMethodException ignored) {
        // exception ignored
    } catch (SecurityException ignored) {
        // exception ignored
    }

    if (method != null && Throwable.class.isAssignableFrom(method.getReturnType())) {
        try {
            return (Throwable) method.invoke(throwable, ArrayUtil.EMPTY_OBJECT_ARRAY);
        } catch (IllegalAccessException ignored) {
            // exception ignored
        } catch (IllegalArgumentException ignored) {
            // exception ignored
        } catch (InvocationTargetException ignored) {
            // exception ignored
        }
    }
    return null;
}

From source file:com.cloudera.nav.plugin.model.ValidationUtil.java

public void validateRequiredMProperties(Object mPropertyObj) {
    for (Method method : mPropertyObj.getClass().getMethods()) {
        if (!method.isBridge() && method.isAnnotationPresent(MProperty.class)
                && method.getAnnotation(MProperty.class).required()) {
            Class<?> returnType = method.getReturnType();
            Object value;/*  w ww .  ja  v  a 2  s .co  m*/
            try {
                value = method.invoke(mPropertyObj);
            } catch (IllegalAccessException e) {
                throw new IllegalArgumentException("Could not access MProperty method " + method.getName(), e);
            } catch (InvocationTargetException e) {
                throw new IllegalArgumentException("Could not get MProperty value for " + method.getName(), e);
            }
            if (Collection.class.isAssignableFrom(returnType)) {
                Preconditions.checkArgument(!CollectionUtils.isEmpty((Collection) value),
                        method.getName() + " returned empty collection");
            } else if (String.class.isAssignableFrom(returnType)) {
                Preconditions.checkArgument(!StringUtils.isEmpty((String) value),
                        method.getName() + " returned null or empty string");
            } else {
                Preconditions.checkArgument(value != null, method.getName() + " returned null");
            }
        }
    }
}

From source file:com.netflix.hystrix.contrib.javanica.utils.FallbackMethod.java

public void validateReturnType(Method commandMethod) {
    if (isPresent()) {
        Class<?> commandReturnType = commandMethod.getReturnType();
        if (ExecutionType.OBSERVABLE == ExecutionType.getExecutionType(commandReturnType)) {
            if (ExecutionType.OBSERVABLE != getExecutionType()) {
                Type commandParametrizedType = commandMethod.getGenericReturnType();
                if (isReturnTypeParametrized(commandMethod)) {
                    commandParametrizedType = getFirstParametrizedType(commandMethod);
                }/*w w w.  j a va2 s  .c  om*/
                validateParametrizedType(commandParametrizedType, method.getGenericReturnType(), commandMethod,
                        method);
            } else {
                validateReturnType(commandMethod, method);
            }

        } else if (ExecutionType.ASYNCHRONOUS == ExecutionType.getExecutionType(commandReturnType)) {
            if (isCommand() && ExecutionType.ASYNCHRONOUS == getExecutionType()) {
                validateReturnType(commandMethod, method);
            }
            if (ExecutionType.ASYNCHRONOUS != getExecutionType()) {
                Type commandParametrizedType = commandMethod.getGenericReturnType();
                if (isReturnTypeParametrized(commandMethod)) {
                    commandParametrizedType = getFirstParametrizedType(commandMethod);
                }
                validateParametrizedType(commandParametrizedType, method.getGenericReturnType(), commandMethod,
                        method);
            }
            if (!isCommand() && ExecutionType.ASYNCHRONOUS == getExecutionType()) {
                throw new FallbackDefinitionException(createErrorMsg(commandMethod, method,
                        "fallback cannot return Future if the fallback isn't command when the command is async."));
            }
        } else {
            if (ExecutionType.ASYNCHRONOUS == getExecutionType()) {
                throw new FallbackDefinitionException(createErrorMsg(commandMethod, method,
                        "fallback cannot return Future if command isn't asynchronous."));
            }
            if (ExecutionType.OBSERVABLE == getExecutionType()) {
                throw new FallbackDefinitionException(createErrorMsg(commandMethod, method,
                        "fallback cannot return Observable if command isn't observable."));
            }
            validateReturnType(commandMethod, method);
        }

    }
}

From source file:com.github.helenusdriver.commons.lang3.reflect.ReflectionUtils.java

/**
 * Gets annotations that are associated with the specified element. If there
 * are no annotations associated with the element, the return value is an
 * empty map. The difference between this method and
 * {@link AnnotatedElement#getAnnotationsByType(Class)} is that this method
 * works on annotation classes that are annotated with the {@link Keyable}
 * annotation in order to determine the key of each annotation. For this to
 * work, the annotated class must defined a key element as defined in the
 * {@link Keyable} annotation of the same return type as specified in
 * <code>keyClass</code>. If its argument is a repeatable annotation type
 * (JLS 9.6), this method, attempts to find one or more annotations of that
 * type by "looking through" a container annotation. The caller of this method
 * is free to modify the returned map; it will have no effect on the maps
 * returned to other callers./*ww  w .ja  va2 s .  c om*/
 * <p>
 * This method will look for both the specified annotation and if the
 * annotation is annotated with {@link Repeatable}, it will also look for this
 * containing annotation which must have a <code>value()</code>
 * element with an array type of the specified annotation. The resulting
 * array will always start with the annotation itself if found followed by
 * all of those provided by the containing annotation.
 *
 * @author paouelle
 *
 * @param <K> the type of the keys to find
 * @param <T> the type of the annotation to query for and return if present
 *
 * @param  keyClass the class of the keys to find and return
 * @param  annotationClass the type of annotations to retrieve
 * @param  annotatedElement the element from which to retrieve the annotations
 * @return a non-<code>null</code> ordered map of annotations associated with the
 *         given element properly keyed as defined in each annotation (may be
 *         empty if none found)
 * @throws NullPointerException if <code>annotatedElement</code>,
 *         <code>annotationClass</code> or <code>keyClass</code> is
 *         <code>null</code>
 * @throws IllegalArgumentException if <code>annotationClass</code> is not
 *         annotated with {@link Keyable} or if the containing annotation
 *         doesn't define a <code>value()</code> element returning an array
 *         of type <code>annotationClass</code> or if <code>annotationClass</code>
 *         doesn't define an element named as specified in its {@link Keyable}
 *         annotation that returns a value of the same class as <code>keyClass</code>
 *         or again if a duplicated keyed annotation is found
 */
@SuppressWarnings("unchecked")
public static <K, T extends Annotation> Map<K, T> getAnnotationsByType(Class<K> keyClass,
        Class<T> annotationClass, AnnotatedElement annotatedElement) {
    org.apache.commons.lang3.Validate.notNull(annotationClass, "invalid null annotation class");
    org.apache.commons.lang3.Validate.notNull(annotatedElement, "invalid null annotation element");
    org.apache.commons.lang3.Validate.notNull(keyClass, "invalid null key class");
    final Keyable k = annotationClass.getAnnotation(Keyable.class);

    org.apache.commons.lang3.Validate.isTrue(k != null, "annotation @%s not annotated with @Keyable",
            annotationClass.getName());
    final Method km;

    try {
        km = annotationClass.getMethod(k.value());
    } catch (NoSuchMethodException e) {
        throw new IllegalArgumentException(
                "annotation key element @" + annotationClass.getName() + "." + k.value() + "() not found", e);
    }
    org.apache.commons.lang3.Validate.isTrue(keyClass.isAssignableFrom(km.getReturnType()),
            "annotation key element @%s.%s() doesn't return class: %s", annotationClass.getName(), k.value(),
            keyClass.getName());
    final T[] as = annotatedElement.getAnnotationsByType(annotationClass);

    if (as.length == 0) {
        return Collections.emptyMap();
    }
    final Map<K, T> map = new LinkedHashMap<>(as.length);

    for (T a : as) {
        final K ak;

        try {
            ak = (K) km.invoke(a);
        } catch (IllegalAccessException e) { // not expected
            throw new IllegalStateException(e);
        } catch (InvocationTargetException e) {
            final Throwable t = e.getTargetException();

            if (t instanceof Error) {
                throw (Error) t;
            } else if (t instanceof RuntimeException) {
                throw (RuntimeException) t;
            } else { // not expected
                throw new IllegalStateException(e);
            }
        }
        org.apache.commons.lang3.Validate.isTrue(map.put(ak, a) == null,
                "duplicate key '%s' found in annotation @%s", ak, annotationClass.getName());
    }
    return map;
}

From source file:com.agileapes.couteau.context.spring.event.impl.AbstractMappedEventsTranslationScheme.java

@Override
public void fillIn(Event originalEvent, ApplicationEvent translated) throws EventTranslationException {
    for (Method method : originalEvent.getClass().getMethods()) {
        if (!method.getName().matches("set[A-Z].*") || !Modifier.isPublic(method.getModifiers())
                || !method.getReturnType().equals(void.class) || method.getParameterTypes().length != 1) {
            continue;
        }//from  ww  w .  java  2s. com
        final String propertyName = StringUtils.uncapitalize(method.getName().substring(3));
        final Field field = ReflectionUtils.findField(translated.getClass(), propertyName);
        if (field == null || !method.getParameterTypes()[0].isAssignableFrom(field.getType())) {
            continue;
        }
        field.setAccessible(true);
        try {
            method.invoke(originalEvent, field.get(translated));
        } catch (Exception e) {
            throw new EventTranslationException("Failed to set property on original event: " + propertyName, e);
        }
    }
}