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:de.hybris.platform.webservices.util.objectgraphtransformer.impl.AbstractNodeConfig.java

/**
 * Creates a lookup map containing all properties of passed type.
 * <p/>/*from  ww w .j  a  v  a 2 s .com*/
 * Result maps a property name to a {@link PropertyConfig}.
 * </p>
 * Any property which keeps java bean standard is found and used for {@link PropertyConfig} creation. For finding all
 * properties {@link Introspector} is used which returns general {@link PropertyDescriptor}. But read- and write
 * methods provided by {@link PropertyDescriptor} are only used as "suggestion" here and are getting post-processed
 * to assure following criteria:
 * <p/>
 * - no bridge or synthetic methods are allowed <br/>
 * - co-variant return types are handled correctly <br/>
 * 
 * @param type
 * @return
 */
private Map<String, PropertyConfig> createPropertiesFor(Class<?> type) {
    final Map<String, PropertyConfig> result = new TreeMap<String, PropertyConfig>();
    final Set<String> done = new HashSet<String>();
    while (type != null) {
        // we are only interested in declared methods (no bridge/synthetic ones)
        final Method[] methods = type.getDeclaredMethods();
        for (final Method method : methods) {
            // only public, non-bridged methods are of interest
            if (!method.isBridge() && Modifier.isPublic(method.getModifiers())) {
                // potential bean-getter property?
                if (method.getParameterTypes().length == 0 && method.getReturnType() != void.class) {
                    // not processed yet?
                    final String methodName = method.getName();
                    if (!done.contains(methodName)) {
                        done.add(methodName);

                        final Matcher matcher = BEAN_GETTER.matcher(methodName);
                        String propertyName = null;
                        if (matcher.matches()) {
                            propertyName = matcher.group(1);
                        } else {
                            if (method.getReturnType().equals(boolean.class)) {
                                final Matcher matcher2 = BEAN_BOOLEAN_GETTER.matcher(methodName);
                                if (matcher2.matches()) {
                                    propertyName = matcher2.group(1);
                                }
                            }
                        }

                        if (propertyName != null) {
                            propertyName = normalizePropertyName(propertyName);

                            // get or create a PropertyConfig
                            DefaultPropertyConfig pCfg = (DefaultPropertyConfig) result.get(propertyName);
                            if (pCfg == null) {
                                pCfg = new DefaultPropertyConfig(propertyName, null, null);
                                result.put(propertyName, pCfg);
                            }
                            pCfg.setReadMethod(method);
                        }
                    }
                }

                // potential bean-setter property?
                if (method.getParameterTypes().length == 1 && method.getReturnType() == void.class) {
                    // not processed yet?
                    final String methodName = method.getName();
                    if (!done.contains(methodName)) {
                        done.add(methodName);
                        final Matcher setter = BEAN_SETTER.matcher(methodName);
                        if (setter.matches()) {
                            String propertyName = setter.group(1);
                            propertyName = Character.toLowerCase(propertyName.charAt(0))
                                    + propertyName.substring(1);

                            // get or create a PropertyConfig
                            DefaultPropertyConfig pCfg = (DefaultPropertyConfig) result.get(propertyName);
                            if (pCfg == null) {
                                pCfg = new DefaultPropertyConfig(propertyName, null, null);
                                result.put(propertyName, pCfg);
                            }
                            pCfg.setWriteMethod(method);
                        }
                    }
                }
            }

        }
        type = type.getSuperclass();
    }
    return result;
}

From source file:com.nominanuda.hyperapi.HyperApiHttpInvocationHandler.java

@Nullable
private Object decode(Class<?> hyperApi2, Method method, HttpResponse resp)
        throws UnsupportedEncodingException, IllegalStateException, IOException, ParseException, SAXException {
    if (resp.getEntity() == null || resp.getEntity().getContent() == null) {
        return null;
    }/*  w w w  .  j  a  v a  2s  .c  om*/
    return entityCodec.decode(resp.getEntity(),
            new AnnotatedType(method.getReturnType(), method.getAnnotations()));
}

From source file:com.p5solutions.core.jpa.orm.MapUtilityImpl.java

/**
 * @see com.p5solutions.core.jpa.orm.MapUtility#map(com.p5solutions.core.jpa.orm.ParameterBinder,
 *      java.lang.Object, java.lang.Object, java.lang.String)
 *///  ww w. ja v  a 2s  .c  o  m
@Override
public Object map(ParameterBinder pb, Object target, Object value, String bindingPath) {
    Class<?> targetClazz = target.getClass();
    String[] p = bindingPath.split("\\.", 2);

    // get the getter and setter methods using the first part of the path, for example address.line1 : p[0] = address.
    Method[] methods = getMethodsGetterAndSetter(targetClazz, p[0]);
    if (methods != null) {

        Method get = methods[0];
        Method set = methods[1];

        // whats the return type of the getter method?
        Class<?> targetType = get.getReturnType();
        // NOT, SINCE IT COULD BE RECURSIVE e.g. @Embedded      Class<?> targetType = pb.getTargetValueType();

        // if the length of p is equal == to 1, then we've hit the end
        // of the path
        if (p.length == 1) {
            // convert the parameter type
            try {
                value = convertValueForEntityFromSQL(pb, value, bindingPath, targetType);
            } catch (TypeConversionException e) {
                throw new RuntimeException(
                        "Unable map data due to conversion problem, please check target class " + targetClazz
                                + " for the problem when binding path " + bindingPath,
                        e);
            }

            // only map the object to the target entity property if the 
            // value is assignable to the target type, otherwise reject it.    
            if (value != null && !targetType.isAssignableFrom(value.getClass())) {
                // value is not assignable to target property.
                logger.error("The value [" + value + "] of type [" + value.getClass()
                        + "] is not assignable to target type [" + targetType + "] on " + pb.getEntityClass()
                        + "->" + pb.getBindingName());
                value = null;
            }

            // finally set the value at the last path
            ReflectionUtility.setValue(set, target, value);

        } else if (p.length == 2) {
            // if p length == to 2 the, continue to recursively walk the graph.
            Class<?> nextClass = get.getReturnType();
            Object next = ReflectionUtility.getValue(get, target);
            if (next == null) {
                next = ReflectionUtility.newInstance(nextClass);
                ReflectionUtility.setValue(set, target, next);
            }

            // try to map the value to the next available path
            return map(pb, next, value, p[1]);
        }
    }
    return target;

    /*
     * // if the length of p is > 0 then the path is valid. if (p.length > 0) {
     * 
     * // get the field name from index 0, since we only splice by a // maximum
     * of 2 String fieldName = p[0];
     * 
     * // find the getter method, make sure it exists Method getterMethod =
     * ReflectionUtility.findGetterMethod( targetClazz, fieldName); if
     * (getterMethod == null) { throw new RuntimeException(new
     * NoSuchMethodException( "No getter method found when using field name [" +
     * fieldName + "] as search pattern!")); }
     * 
     * // find the setter method, make sure it exists Method setterMethod =
     * ReflectionUtility.findSetterMethod( targetClazz, getterMethod); if
     * (setterMethod == null) { throw new RuntimeException(new
     * NoSuchMethodException( "No setter method found when using field name [" +
     * fieldName + "] as search pattern!")); }
     * 
     * // whats the return type of the getter method? Class<?> targetType =
     * getterMethod.getReturnType();
     * 
     * // if the length of p is equal == to 1, then we've hit the end // of the
     * path if (p.length == 1) { // convert the parameter type value =
     * convertValue(value, targetType);
     * 
     * // finally set the value at the last path
     * ReflectionUtility.setValue(setterMethod, target, value); } else if
     * (p.length == 2) {
     * 
     * // if p length == to 2 the, continue to recursively walk the // graph.
     * Class<?> nextClass = getterMethod.getReturnType(); Object nextTarget =
     * ReflectionUtility.getValue(getterMethod, target); if (nextTarget == null)
     * { nextTarget = ReflectionUtility.newInstance(nextClass);
     * ReflectionUtility .setValue(setterMethod, target, nextTarget); }
     * 
     * // try to map the value to the next available path return map(nextTarget,
     * value, p[1]); } } return target;
     */
}

From source file:info.archinnov.achilles.helper.EntityIntrospector.java

public Method findGetter(Class<?> beanClass, Field field) {
    log.debug("Find getter for field {} in class {}", field.getName(), beanClass.getCanonicalName());

    Method getterMethod = null;
    String fieldName = field.getName();
    String[] getters = this.deriveGetterName(field);

    for (String getter : getters) {
        try {/*from   w  w  w .java 2 s  .co  m*/
            getterMethod = beanClass.getMethod(getter);
            if (getterMethod.getReturnType() != field.getType()) {
                throw new AchillesBeanMappingException("The getter for field '" + fieldName + "' of type '"
                        + field.getDeclaringClass().getCanonicalName() + "' does not return correct type");
            }
        } catch (NoSuchMethodException e) {
            // Do nothing here
        }
    }
    if (getterMethod == null) {
        throw new AchillesBeanMappingException("The getter for field '" + fieldName + "' of type '"
                + field.getDeclaringClass().getCanonicalName() + "' does not exist");
    }

    log.trace("Derived getter method : {}", getterMethod.getName());
    return getterMethod;
}

From source file:com.googlecode.jdbcproc.daofactory.impl.block.service.ResultSetConverterBlockServiceImpl.java

public IResultSetConverterBlock create(Method daoMethod, StoredProcedureInfo procedureInfo,
        ParameterConverterService converterService) {
    Class returnType = daoMethod.getReturnType();
    if (returnType.equals(void.class)) {
        // void//from   ww  w .j a va2 s. com
        return null;

    } else if (BlockFactoryUtils.isReturnRowIterator(daoMethod)) { // returns RowIterator FIXME think about input columns (dynamic)
        return new ResultSetConverterRowIterator();

        // OUTPUT PARAMETER HAS RETURN
    } else if (BlockFactoryUtils.isOneOutputHasReturn(daoMethod, procedureInfo)) {
        return null;

    } else if (BlockFactoryUtils.isSimpleType(returnType)) {
        // simple type from result set
        return createBlockSimpleType(converterService, returnType, procedureInfo);

    } else if (returnType.isAssignableFrom(List.class)) {
        // LIST
        Class entityClass = getEntityClass(daoMethod);
        if (BlockFactoryUtils.isSimpleType(entityClass)) {
            // simple type for list
            return createBlockSimpleTypeList(converterService, entityClass, procedureInfo);

        } else if (isOneToManyPresent(entityClass)) {
            // @OneToMany Annotation support
            return new ResultSetConverterBlockEntityOneToMany2xList(
                    createEntityBlockOneToMany2xList(converterService, entityClass, procedureInfo));

        } else {
            // Without @OneToMany Annotation
            ResultSetConverterBlockEntity blockEntity = createEntityBlock(converterService, entityClass,
                    procedureInfo);
            return new ResultSetConverterBlockEntityList(blockEntity);
        }

    } else if (BlockFactoryUtils.isReturnIterator(daoMethod)) {
        // Iterator
        Class entityClass = getEntityClass(daoMethod);
        if (BlockFactoryUtils.isSimpleType(entityClass)) {
            // simple type for iterator
            return createBlockSimpleTypeIterator(converterService, entityClass, procedureInfo);

        } else if (isOneToManyPresent(entityClass)) {
            // @OneToMany Annotation not supported
            throw new IllegalStateException("Iterator with OneToMany is unsupported");
        } else {
            // Without @OneToMany Annotation
            ResultSetConverterBlockEntity blockEntity = createEntityBlock(converterService, entityClass,
                    procedureInfo);
            return new ResultSetConverterBlockEntityIterator(blockEntity);
        }

    } else if (returnType.isAssignableFrom(Collection.class)) {
        // collection
        throw new IllegalStateException("Unsupported return type " + daoMethod.getReturnType().getSimpleName());

    } else {
        // entity may be
        if (isOneToManyPresent(returnType)) {
            // @OneToMany annotation is finded
            return new ResultSetConverterBlockEntityOneToMany2x(
                    createEntityBlockOneToMany2xList(converterService, returnType, procedureInfo));
        } else {
            return createEntityBlock(converterService, returnType, procedureInfo);
        }
    }
}

From source file:net.servicefixture.fitnesse.FixtureTemplateCreator.java

/**
 * Generates the test table template for the ServiceFixture and prints out
 * to standard console./* w w w . jav a  2  s  . c o  m*/
 *
 * @param clazz
 */
private void generateServiceFixtureTemplate(Class clazz) throws Exception {
    ServiceFixture fixture = (ServiceFixture) clazz.newInstance();
    Method operation = fixture.getServiceOperation();
    if (operation == null) {
        writeLine("Unable to generate template for fixture:" + fixture.getClass().getName()
                + " because service operation is unknown.");
        return;
    }
    Class[] parameterTypes = operation.getParameterTypes();
    Class returnType = operation.getReturnType();
    for (int i = 0; i < parameterTypes.length; i++) {
        String prefix = "|set|" + getParameterName(parameterTypes[i]);
        Stack<Class> ancestors = new Stack<Class>();
        ancestors.push(CollectionBuilderFactory.getElementType(parameterTypes[i]));
        addTableRowsForType(ancestors, prefix, CollectionBuilderFactory.getElementType(parameterTypes[i]),
                true);
    }

    writeLine("|invoke||");

    if ("void".equals(returnType.getName())) {
        writeLine("|check|response == null|true|");
    } else {
        writeLine("|check|response != null|true|");

        String prefix = "|check|response";
        if (CollectionBuilderFactory.isCollectionType(returnType)) {
            writeLine("|check|response.size() > 0|true|");
            writeLine("|check|response.size()||");
            prefix = prefix + "[0]";
        }
        Stack<Class> ancestors = new Stack<Class>();
        ancestors.push(CollectionBuilderFactory.getElementType(returnType));
        addTableRowsForType(ancestors, prefix, CollectionBuilderFactory.getElementType(returnType), false);
    }
}

From source file:net.camelpe.extension.camel.typeconverter.CdiTypeConverterBuilder.java

private TypeConverterHolder buildTypeConverterFromConverterAnnotatedClass(final Class<?> type,
        final Method method) throws IllegalArgumentException {
    ensureConverterMethodIsValid(type, method);
    this.log.trace("Building TypeConverter from method [{}] ...", method);
    final TypeConverter typeConverter;
    final Class<?> fromType = method.getParameterTypes()[0];
    final Class<?> toType = method.getReturnType();
    if (isStatic(method.getModifiers())) {
        typeConverter = new StaticMethodTypeConverter(method);
    } else {//from w  ww . j  a v  a 2s.c o m
        typeConverter = new CdiInstanceMethodTypeConverter(new CdiInjector(this.beanManager), method,
                this.typeConverterRegistry);
    }
    this.log.trace("Built TypeConverter [{}]", typeConverter, method);

    return TypeConverterHolder.newNonFallbackTypeConverterHolder(fromType, toType, typeConverter);
}

From source file:org.socialsignin.spring.data.dynamodb.repository.support.DynamoDBHashAndRangeKeyExtractingEntityMetadataImpl.java

public DynamoDBHashAndRangeKeyExtractingEntityMetadataImpl(final Class<T> domainType) {
    super(domainType);
    this.hashAndRangeKeyMethodExtractor = new DynamoDBHashAndRangeKeyMethodExtractorImpl<T>(getJavaType());
    ReflectionUtils.doWithMethods(domainType, new MethodCallback() {
        public void doWith(Method method) {
            if (method.getAnnotation(DynamoDBHashKey.class) != null) {
                String setterMethodName = toSetterMethodNameFromAccessorMethod(method);
                if (setterMethodName != null) {
                    hashKeySetterMethod = ReflectionUtils.findMethod(domainType, setterMethodName,
                            method.getReturnType());
                }/* w w  w.ja v  a  2 s  .  co m*/
            }
        }
    });
    ReflectionUtils.doWithFields(domainType, new FieldCallback() {
        public void doWith(Field field) {
            if (field.getAnnotation(DynamoDBHashKey.class) != null) {

                hashKeyField = ReflectionUtils.findField(domainType, field.getName());

            }
        }
    });
    Assert.isTrue(hashKeySetterMethod != null || hashKeyField != null,
            "Unable to find hash key field or setter method on " + domainType + "!");
    Assert.isTrue(hashKeySetterMethod == null || hashKeyField == null,
            "Found both hash key field and setter method on " + domainType + "!");

}

From source file:edu.wustl.bulkoperator.processor.AbstractBulkOperationProcessor.java

private void setContainmentObjectProperty(BulkOperationClass containmentMigrationClass, Object mainObject,
        String name, Collection valueToSet) throws Exception {
    /*/*from   w ww. jav  a  2 s. co m*/
     * This method is introduced to handle List type Containment assignment
     * Do not use getField() or getDeclaredField() to simplify the below processing
     * #1 getField() doesn't fetch private fields of class
     * #2 getDeclaredField() can fetch private fields of class, but can't fetch fields that are inherited from parent class
     */

    String getterMethod = "get" + Character.toUpperCase(name.charAt(0)) + name.substring(1);
    Method method = mainObject.getClass().getMethod(getterMethod, null);

    if (List.class.getName().equals(method.getReturnType().getName())) {
        valueToSet = new ArrayList(valueToSet);
    }

    BeanUtils.setProperty(mainObject, name, valueToSet);
}

From source file:fr.putnami.pwt.core.service.server.service.CommandExecutorImpl.java

public CommandExecutorImpl(Object service, Method method) {
    this.service = service;
    this.method = method;

    String[] paramTypes = new String[method.getParameterTypes().length];

    for (int i = 0; i < method.getParameterTypes().length; i++) {
        paramTypes[i] = method.getParameterTypes()[i].getCanonicalName();
    }//from  w w  w . ja v a 2s.  co  m
    CommandDefinition definition = new CommandDefinition(method.getDeclaringClass().getName(), method.getName(),
            method.getReturnType().getCanonicalName(), paramTypes);
    this.setCommandDefinition(definition);

    this.executorLogger = LogFactory.getLog(method.getDeclaringClass().getCanonicalName());
}