Example usage for java.lang.reflect Method getGenericReturnType

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

Introduction

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

Prototype

public Type getGenericReturnType() 

Source Link

Document

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

Usage

From source file:cn.wanghaomiao.seimi.core.SeimiBeanResolver.java

private static Object defaultCastToTargetValue(Class target, Field field, List<Object> xpathRes) {
    Method getter = ReflectionUtils.findMethod(target, "get" + upperFirst(field.getName()));
    if (getter != null) {
        if (List.class.equals(getter.getReturnType())) {
            Class[] componentClazzs = GenericUtils.getActualClass(getter.getGenericReturnType());
            if (componentClazzs != null && componentClazzs.length > 0) {
                Class componentClass = componentClazzs[0];
                if (String.class.isAssignableFrom(componentClass)) {
                    List<String> resTmp = new LinkedList<>();
                    for (Object obj : xpathRes) {
                        if (obj instanceof Element) {
                            resTmp.add(((Element) obj).html());
                        } else {
                            resTmp.add(obj.toString());
                        }// w w w.  j  a va 2 s  .  co  m
                    }
                    return resTmp;
                } else if (Element.class.isAssignableFrom(componentClass)) {
                    return xpathRes;
                } else if (GenericUtils.isNumber(componentClass)) {
                    List resTmp = new LinkedList();
                    for (Object obj : xpathRes) {
                        resTmp.add(GenericUtils.castToNumber(componentClass, obj.toString()));
                    }
                    return resTmp;
                } else {
                    throw new SeimiBeanResolveException("not support field type");
                }
            }
        } else if (!Collection.class.isAssignableFrom(getter.getReturnType())
                && getter.getReturnType().isArray()) {
            Class componentClass = getter.getReturnType().getComponentType();
            if (String.class.isAssignableFrom(componentClass)) {
                List<String> resTmp = new LinkedList<>();
                for (Object obj : xpathRes) {
                    if (obj instanceof Element) {
                        resTmp.add(((Element) obj).html());
                    } else {
                        resTmp.add(obj.toString());
                    }
                }
                return resTmp;
            } else if (Element.class.isAssignableFrom(componentClass)) {
                return xpathRes;
            } else if (GenericUtils.isNumber(componentClass)) {
                List resTmp = new LinkedList();
                for (Object obj : xpathRes) {
                    resTmp.add(GenericUtils.castToNumber(componentClass, obj.toString()));
                }
                return resTmp;
            } else {
                throw new SeimiBeanResolveException("not support field type");
            }
        } else if (!Collection.class.isAssignableFrom(getter.getReturnType())
                && GenericUtils.isNumber(field.getType())) {
            return GenericUtils.castToNumber(field.getType(), StringUtils.join(xpathRes, ""));
        } else if (!Collection.class.isAssignableFrom(getter.getReturnType())
                && String.class.isAssignableFrom(field.getType())) {
            return StringUtils.join(xpathRes, "");
        }
    }
    return null;
}

From source file:com.revolsys.util.JavaBeanUtil.java

public static Class<?> getTypeParameterClass(final Method method, final Class<?> expectedRawClass) {
    final Type resultListReturnType = method.getGenericReturnType();
    if (resultListReturnType instanceof ParameterizedType) {
        final ParameterizedType parameterizedType = (ParameterizedType) resultListReturnType;
        final Type rawType = parameterizedType.getRawType();
        if (rawType == expectedRawClass) {
            final Type[] typeArguments = parameterizedType.getActualTypeArguments();
            if (typeArguments.length == 1) {
                final Type resultType = typeArguments[0];
                if (resultType instanceof Class<?>) {
                    final Class<?> resultClass = (Class<?>) resultType;
                    return resultClass;
                } else {
                    throw new IllegalArgumentException(method.getName() + " must return "
                            + expectedRawClass.getName() + " with 1 generic type parameter that is a class");
                }/*from   www  .  jav  a2  s. co  m*/
            }
        }
    }
    throw new IllegalArgumentException(method.getName() + " must return " + expectedRawClass.getName()
            + " with 1 generic class parameter");
}

From source file:org.talend.dataprep.conversions.BeanConversionService.java

/**
 * The {@link BeanUtils#copyProperties(java.lang.Object, java.lang.Object)} method does <b>NOT</b> check if parametrized type
 * are compatible when copying values, this helper method performs this additional check and ignore copy of those values.
 *
 * @param source The source bean (from which values are read).
 * @param converted The target bean (to which values are written).
 *//*from  w  w  w.j  a va2s . c o  m*/
private static void copyBean(Object source, Object converted) {
    // Find property(ies) to ignore during copy.
    List<String> discardedProperties = new LinkedList<>();
    final BeanWrapper sourceBean = new BeanWrapperImpl(source);
    final BeanWrapper targetBean = new BeanWrapperImpl(converted);
    final PropertyDescriptor[] sourceProperties = sourceBean.getPropertyDescriptors();
    for (PropertyDescriptor sourceProperty : sourceProperties) {
        if (targetBean.isWritableProperty(sourceProperty.getName())) {
            final PropertyDescriptor targetProperty = targetBean
                    .getPropertyDescriptor(sourceProperty.getName());
            final Class<?> sourcePropertyType = sourceProperty.getPropertyType();
            final Class<?> targetPropertyType = targetProperty.getPropertyType();
            final Method readMethod = sourceProperty.getReadMethod();
            if (readMethod != null) {
                final Type sourceReturnType = readMethod.getGenericReturnType();
                final Method targetPropertyWriteMethod = targetProperty.getWriteMethod();
                if (targetPropertyWriteMethod != null) {
                    final Type targetReturnType = targetPropertyWriteMethod.getParameters()[0]
                            .getParameterizedType();
                    boolean valid = Object.class.equals(targetPropertyType)
                            || sourcePropertyType.equals(targetPropertyType)
                                    && sourceReturnType.equals(targetReturnType);
                    if (!valid) {
                        discardedProperties.add(sourceProperty.getName());
                    }
                }
            } else {
                discardedProperties.add(sourceProperty.getName());
            }
        }
    }

    // Perform copy
    BeanUtils.copyProperties(source, converted,
            discardedProperties.toArray(new String[discardedProperties.size()]));
}

From source file:com.amalto.core.metadata.ClassRepository.java

private static Class<?> getListItemClass(Method declaredMethod, Class<?> returnType) {
    Type genericReturnType = declaredMethod.getGenericReturnType();
    if (genericReturnType instanceof ParameterizedType) {
        Type type = ((ParameterizedType) genericReturnType).getActualTypeArguments()[0];
        if (type instanceof Class<?>) {
            returnType = ((Class) type);
        } else {/*  w w w .  j a v  a 2 s  .co  m*/
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("List returned by " + declaredMethod.getName() + " isn't using generic types.");
            }
            returnType = String.class;
        }
    }
    return returnType;
}

From source file:net.radai.beanz.util.ReflectionUtil.java

public static boolean isSetter(Method method) {
    Type returnType = method.getGenericReturnType();
    if (!returnType.equals(void.class)) {
        return false; //should not return anything
    }//from   ww  w. ja  v a2  s  .c  om
    Type[] argumentTypes = method.getGenericParameterTypes();
    if (argumentTypes == null || argumentTypes.length != 1) {
        return false; //should accept exactly one argument
    }
    String name = method.getName();
    if (name.startsWith("set")) {
        if (name.length() < 4) {
            return false; //setSomething
        }
        String fourthChar = name.substring(3, 4);
        return fourthChar.toUpperCase(Locale.ROOT).equals(fourthChar); //setSomething (upper case)
    }
    return false;
}

From source file:org.alfresco.module.org_alfresco_module_rm.api.PublicAPITestUtil.java

/**
 * Get all types references by the supplied method signature (i.e. the parameters, return type and exceptions).
 *
 * @param method The method to analyse.//from w w  w  .j a  va 2 s.  c o m
 * @return The set of types.
 */
private static Set<Type> getTypesFromMethod(Method method) {
    Set<Type> methodTypes = new HashSet<>();
    methodTypes.addAll(Sets.newHashSet(method.getGenericParameterTypes()));
    methodTypes.add(method.getGenericReturnType());
    methodTypes.addAll(Sets.newHashSet(method.getGenericExceptionTypes()));
    return methodTypes;
}

From source file:net.radai.beanz.util.ReflectionUtil.java

public static boolean isGetter(Method method) {
    Type returnType = method.getGenericReturnType();
    if (returnType.equals(void.class)) {
        return false; //should return something
    }//  w  ww . j  av a  2 s . c  o m
    Type[] argumentTypes = method.getGenericParameterTypes();
    if (argumentTypes != null && argumentTypes.length != 0) {
        return false; //should not accept any arguments
    }
    String name = method.getName();
    if (name.startsWith("get")) {
        if (name.length() < 4) {
            return false; //has to be getSomething
        }
        String fourthChar = name.substring(3, 4);
        return fourthChar.toUpperCase(Locale.ROOT).equals(fourthChar); //getSomething (upper case)
    } else if (name.startsWith("is")) {
        if (name.length() < 3) {
            return false; //isSomething
        }
        String thirdChar = name.substring(2, 3);
        //noinspection SimplifiableIfStatement
        if (!thirdChar.toUpperCase(Locale.ROOT).equals(thirdChar)) {
            return false; //has to start with uppercase (or something that uppercases to itself, like a number?)
        }
        return returnType.equals(boolean.class) || returnType.equals(Boolean.class);
    } else {
        return false;
    }
}

From source file:de.micromata.genome.util.runtime.ClassUtils.java

/**
 * Find generic type from method./*from w w  w  .  jav a 2 s  .c o m*/
 *
 * @param clazz the clazz
 * @param method the method
 * @param pos the pos
 * @return the class
 */
public static Class<?> findGenericTypeFromMethod(Class<?> clazz, Method method, int pos) {
    java.lang.reflect.Type gent = method.getGenericReturnType();
    Class<?> gentype = ClassUtils.findGenericTypeArgument(gent, pos);
    return gentype;
}

From source file:com.github.cherimojava.data.mongo.entity.EntityUtils.java

/**
 * returns true if this getter methods return type is either an entity or a list of entities. Otherwise false
 * /*from   w  w w . j a v  a2  s. c om*/
 * @param getter
 * @return true if return type is entity or list of entities
 */
public static boolean isValidReferenceClass(Method getter) {
    return (Entity.class.isAssignableFrom(getter.getReturnType())
            || (Collection.class.isAssignableFrom(getter.getReturnType()) && Entity.class.isAssignableFrom(
                    (Class) ((ParameterizedType) getter.getGenericReturnType()).getActualTypeArguments()[0])));
}

From source file:org.batoo.jpa.common.reflect.ReflectHelper.java

/**
 * Returns the actual generic type of a class's type parameter of the <code>member</code>.
 * <p>/*from   w w  w.ja v  a2  s . c  om*/
 * if the <code>member</code> is a field then field's generic types are checked. Otherwise the <code>member</code> is treated a a method
 * and its return type's is checked.
 * <p>
 * 
 * @param member
 *            the member
 * @param index
 *            the index number of the generic parameter
 * @return the class of generic type
 * 
 * @param <X>
 *            the type of the class
 * 
 * @since $version
 * @author hceylan
 */
@SuppressWarnings("unchecked")
public static <X> Class<X> getGenericType(Member member, int index) {
    Type type;

    if (member instanceof Field) {
        final Field field = (Field) member;
        type = field.getGenericType();

    } else {
        final Method method = (Method) member;
        type = method.getGenericReturnType();
    }

    // if not a parameterized type return null
    if (!(type instanceof ParameterizedType)) {
        return null;
    }

    final ParameterizedType parameterizedType = (ParameterizedType) type;

    final Type[] types = parameterizedType != null ? parameterizedType.getActualTypeArguments() : null;

    return (Class<X>) ((types != null) && (index < types.length) ? types[index] : null);
}