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:cherry.foundation.testtool.stub.StubServiceImpl.java

@Override
public String thenReturn(String className, String methodName, int methodIndex, final String value,
        final String valueType) {
    return executeWithMapping(className, methodName, methodIndex, new Function<Method, Object>() {
        @Override/*from   www . j ava 2 s  .  c o  m*/
        public Object apply(Method method) {
            JavaType returnType = objectMapper.getTypeFactory().constructType(method.getGenericReturnType());
            if (StringUtils.isNotEmpty(valueType)) {
                returnType = objectMapper.getTypeFactory().constructFromCanonical(valueType);
            }
            try {
                Object v = objectMapper.readValue(value, returnType);
                repository.get(method).thenReturn(v, returnType.toCanonical());
                return Boolean.TRUE;
            } catch (IOException ex) {
                return ToMapUtil.fromThrowable(ex, Integer.MAX_VALUE);
            }
        }
    });
}

From source file:com.evolveum.midpoint.repo.sql.query.definition.ClassDefinitionParser.java

private CollectionDefinition updateCollectionDefinition(CollectionDefinition definition,
        AnnotatedElement object, QName jaxbName, String jpaName) {
    Definition collDef;/*from  w  w  w. j a v a2s  .co m*/
    if (object instanceof Method) {
        Method method = (Method) object;
        ParameterizedType type = (ParameterizedType) method.getGenericReturnType();
        Type type1 = type.getActualTypeArguments()[0];
        Class clazz;
        if (type1 instanceof Class) {
            clazz = ((Class) type1);
        } else {
            clazz = (Class) ((ParameterizedType) type1).getRawType();
        }

        QName realJaxbName = getJaxbName(method);
        Class jaxbType = getJaxbType(clazz);
        String realJpaName = getJpaName(method);
        collDef = createDefinition(realJaxbName, jaxbType, realJpaName, clazz);
    } else {
        Class clazz = (Class) object;

        Class jaxbType = getJaxbType(clazz);
        collDef = createDefinition(jaxbName, jaxbType, jpaName, clazz);
    }

    if (collDef instanceof EntityDefinition) {
        updateEntityDefinition((EntityDefinition) collDef);
    }

    definition.setDefinition(collDef);

    return definition;
}

From source file:de.javadesign.cdi.extension.spring.SpringBeanIntegrationExtension.java

/**
 * Try to create a bean if class is found.
 * /*w w  w  .jav a  2  s  . com*/
 * @param beanName
 *            the bean name to find and create
 * @param beanDefinition
 *            the spring bean definition
 * @param beanManager
 *            the injection bean manager
 * @param beanFactory
 *            a ConfigurableListableBeanFactory
 * @return the created bean or null if class was not found
 */
private Bean<?> createBean(final String beanName, final BeanDefinition beanDefinition,
        final ConfigurableListableBeanFactory beanFactory, final BeanManager beanManager) {
    Class<?> beanClass = null;

    try {
        if (null == beanDefinition.getBeanClassName()) {
            // TODO: Support beans which are created via factory bean.
            LOGGER.warn("Ignored bean with name {} - there is no definition via bean's class name available",
                    beanName);
            return CLASS_NOT_FOUND;
        }
        beanClass = Class.forName(beanDefinition.getBeanClassName());

        // FactoryBean? Bean class is returned by getObjectType method
        for (Class<?> beanClassInterface : beanClass.getInterfaces()) {
            if (!beanClassInterface.equals(FactoryBean.class)) {
                continue;
            }
            try {
                Method getObjectTypeMethod = beanClass.getDeclaredMethod(METHOD_NAME_GET_OBJECT_TYPE);
                String s = ((ParameterizedType) getObjectTypeMethod.getGenericReturnType())
                        .getActualTypeArguments()[0].toString();
                beanClass = Class.forName(s.substring(s.lastIndexOf(" ") + 1));

            } catch (NoSuchMethodException ignored) {
                LOGGER.warn("Ignored bean {} with Class {} that is assumed to be a FactoryBean, "
                        + "but has no getObjectType method.", beanName, beanClass);
                return CLASS_NOT_FOUND;
            }
            break;
        }

    } catch (final ClassNotFoundException e) {
        LOGGER.warn("Class {} not found.", beanName);
        return CLASS_NOT_FOUND;
    }

    final AnnotatedType<?> annotatedType = beanManager.createAnnotatedType(beanClass);
    final Set<Type> beanTypes = annotatedType.getTypeClosure();
    final Set<Annotation> qualifiers = new HashSet<Annotation>();
    qualifiers.add(new AnnotationLiteral<Any>() {

        private static final long serialVersionUID = 1L;
        // any implementation
    });
    qualifiers.add(new AnnotationLiteral<Default>() {

        private static final long serialVersionUID = 1L;
        // default implementation
    });

    final Set<Class<? extends Annotation>> stereotypes = new HashSet<Class<? extends Annotation>>();

    for (final Annotation annotation : annotatedType.getAnnotations()) {
        if (beanManager.isQualifier(annotation.annotationType())) {
            qualifiers.add(annotation);
        }
        if (beanManager.isStereotype(annotation.annotationType())) {
            stereotypes.add(annotation.annotationType());
        }
    }

    return new SpringBean(beanName, beanClass, beanTypes, qualifiers, stereotypes, beanFactory);
}

From source file:org.apache.axis2.jaxws.runtime.description.marshal.impl.PackageSetBuilder.java

/**
 * add package information by reflecting the return type on Method m
 * @param set//from  w w w  .  j  a  v a  2s.c o m
 * @param m
 */
private static void addPackagesFromReturn(TreeSet<String> set, Method m) {
    if (log.isDebugEnabled()) {
        log.debug("enter addPackagesFromReturn for " + m);
    }
    try {
        if (m != null) {
            Set<Class> classes = new HashSet<Class>();
            // Build a set of all of the classes referenced in the return(including
            // generic argument references
            classes = ClassUtils.getClasses(m.getGenericReturnType(), classes);
            addClassesToPackageSet(classes, set);
        }
    } catch (Throwable t) {
        if (log.isDebugEnabled()) {
            log.debug("Could not reflect the information on method " + m + " due to " + t);
            log.debug("Processing continues");
        }
    }
    if (log.isDebugEnabled()) {
        log.debug("exit addPackagesFromReturn");
    }
}

From source file:net.sourceforge.jabm.VariableBindingsIterator.java

@SuppressWarnings({ "rawtypes", "unchecked" })
public Class getType(String beanProperty) {
    int dot = beanProperty.indexOf('.');
    String beanName = beanProperty.substring(0, dot);
    String attributeName = beanProperty.substring(dot + 1);
    Class beanType = beanFactory.getType(beanName);
    String getterName = "get" + Character.toUpperCase(attributeName.charAt(0)) + attributeName.substring(1);
    try {/*  w  ww.  j a  v  a 2  s . com*/
        Method method = beanType.getMethod(getterName, new Class[] {});
        Type returnType = method.getGenericReturnType();
        if (returnType instanceof Class) {
            Class result = (Class) returnType;
            return result;
        } else {
            throw new IllegalArgumentException(beanProperty);
        }
    } catch (NoSuchMethodException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.ocelotds.marshalling.ArgumentServicesTest.java

@Test
public void testCheckTypeParamType() throws JsonUnmarshallingException {
    System.out.println("checkType");
    Method[] methods = this.getClass().getDeclaredMethods();
    Type type = null;//from   w ww .  j a v a 2  s.co  m
    for (Method method : methods) {
        if (method.getName().equals("method")) {
            type = method.getGenericReturnType();
        }
    }
    doNothing().when(instance).checkClass(anyObject(), any(Class.class));
    instance.checkType(mock(List.class), type);
    verify(instance).checkClass(anyObject(), any(Class.class));
}

From source file:com.google.api.server.spi.config.jsonwriter.JacksonResourceSchemaProvider.java

@Nullable
private TypeToken<?> getPropertyType(TypeToken<?> beanType, Method readMethod, Method writeMethod,
        AnnotatedField field, ApiConfig config) {
    if (readMethod != null) {
        // read method's return type is the property type
        return ApiAnnotationIntrospector.getSchemaType(beanType.resolveType(readMethod.getGenericReturnType()),
                config);//from   w w w  . j a  v a2 s  .  c  o  m
    } else if (writeMethod != null) {
        Type[] paramTypes = writeMethod.getGenericParameterTypes();
        if (paramTypes.length == 1) {
            // write method's first parameter type is the property type
            return ApiAnnotationIntrospector.getSchemaType(beanType.resolveType(paramTypes[0]), config);
        }
    } else if (field != null) {
        return ApiAnnotationIntrospector.getSchemaType(beanType.resolveType(field.getGenericType()), config);
    }
    return null;
}

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

@Test
public void arrayItemTypeIsSingularFormOfPropertyName() throws NoSuchMethodException {

    Method getterMethod = classWithArrayProperties.getMethod("getThings");

    // assert List<Thing>
    Class<?> genericType = (Class<?>) ((ParameterizedType) getterMethod.getGenericReturnType())
            .getActualTypeArguments()[0];
    assertThat(genericType.getName(), is("com.example.Thing"));

}

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

@Test
public void arrayItemTypeIsSingularFormOfPropertyNameWhenNameEndsInIES() throws NoSuchMethodException {

    Method getterMethod = classWithArrayProperties.getMethod("getProperties");

    // assert List<Property>
    Class<?> genericType = (Class<?>) ((ParameterizedType) getterMethod.getGenericReturnType())
            .getActualTypeArguments()[0];
    assertThat(genericType.getName(), is("com.example.Property"));

}

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

@Test
public void uniqueArraysAreSets() throws NoSuchMethodException {

    Method getterMethod = classWithArrayProperties.getMethod("getUniqueArray");

    assertThat(getterMethod.getReturnType().getName(), is(Set.class.getName()));
    assertThat(getterMethod.getGenericReturnType(), is(instanceOf(ParameterizedType.class)));

    Type genericType = ((ParameterizedType) getterMethod.getGenericReturnType()).getActualTypeArguments()[0];
    assertThat(genericType, is(instanceOf(Class.class)));
    assertThat(((Class<?>) genericType).getName(), is(Boolean.class.getName()));

}