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:com.sinosoft.one.data.jade.statement.StatementMetaData.java

public StatementMetaData(DAOMetaData daoMetaData, Method method, String sqlQuerie) {
    this.daoMetaData = daoMetaData;
    this.method = method;
    this.sql = method.getAnnotation(SQL.class) == null ? sqlQuerie : method.getAnnotation(SQL.class).value();

    this.genericReturnTypes = GenericUtils.getActualClass(method.getGenericReturnType());

    Annotation[][] annotations = method.getParameterAnnotations();
    this.parameterCount = annotations.length;
    this.sqlParams = new Param[annotations.length];
    int shardByIndex = -1;
    for (int index = 0; index < annotations.length; index++) {
        for (Annotation annotation : annotations[index]) {
            if (annotation instanceof ShardBy) {
                if (shardByIndex >= 0) {
                    throw new IllegalArgumentException("duplicated @" + ShardBy.class.getName());
                }/*from w  ww  . j av a 2 s. c  o m*/
                shardByIndex = index;
            } else if (annotation instanceof Param) {
                this.sqlParams[index] = (Param) annotation;
            }
        }
    }
    this.shardByIndex = shardByIndex;
}

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

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

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

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

    Method getter = classWithNoAdditionalProperties.getMethod("getAdditionalProperties");

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

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

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

}

From source file:com.stehno.sjdbcx.reflection.extractor.RowMapperExtractor.java

public RowMapper extract(final Method method) {
    final com.stehno.sjdbcx.annotation.RowMapper mapper = AnnotationUtils.getAnnotation(method,
            com.stehno.sjdbcx.annotation.RowMapper.class);
    if (mapper == null) {
        Class mappedType = method.getReturnType();

        if (Collection.class.isAssignableFrom(mappedType)) {
            mappedType = (Class) ((ParameterizedType) method.getGenericReturnType())
                    .getActualTypeArguments()[0];

        } else if (mappedType.isArray()) {
            throw new UnsupportedOperationException("Auto-mapping for array return types is not yet supported");

        } else if (mappedType.isPrimitive()) {
            if (mappedType == int.class || mappedType == long.class) {
                return new SingleColumnRowMapper();

            } else if (mappedType == boolean.class) {
                return new RowMapper<Boolean>() {
                    @Override/*from w w w  .ja  va2 s .  com*/
                    public Boolean mapRow(final ResultSet resultSet, final int i) throws SQLException {
                        return resultSet.getBoolean(1);
                    }
                };
            }
        }

        return new BeanPropertyRowMapper(mappedType);

    } else {
        final String extractKey = mapper.value();
        if (StringUtils.isEmpty(extractKey)) {
            return resolve((Class<RowMapper>) mapper.type());
        } else {
            return resolve(extractKey);
        }
    }
}

From source file:me.crime.loader.DataBaseLoader.java

private void saveData(String method, String data, Object obj) throws SAXException {
    Method getMethod = getMethod("get" + method, obj);
    Method setMethod = getMethod("set" + method, obj);

    try {//from  w w  w. j  ava  2  s . com

        Object args[] = new Object[1];
        if (getMethod.getGenericReturnType() == Integer.TYPE) {
            args[0] = new Integer(data);
        } else if (getMethod.getGenericReturnType() == String.class) {
            args[0] = data;
        } else if (getMethod.getGenericReturnType() == Double.TYPE) {
            args[0] = new Double(data);
        } else if (getMethod.getGenericReturnType() == Long.TYPE) {
            args[0] = new Long(data);
        } else if (getMethod.getGenericReturnType() == Calendar.class) {
            String[] dt = data.split(":");
            Calendar cal = Calendar.getInstance();

            cal.set(Calendar.YEAR, Integer.parseInt(dt[0]));
            cal.set(Calendar.MONTH, Integer.parseInt(dt[1]));
            cal.set(Calendar.DAY_OF_MONTH, Integer.parseInt(dt[2]));
            cal.set(Calendar.HOUR_OF_DAY, Integer.parseInt(dt[3]));
            cal.set(Calendar.MINUTE, Integer.parseInt(dt[4]));
            cal.set(Calendar.SECOND, Integer.parseInt(dt[5]));
            cal.set(Calendar.MILLISECOND, Integer.parseInt(dt[5]));

            if (cal.get(Calendar.YEAR) < 10) {
                cal.set(Calendar.YEAR, 2000 + cal.get(Calendar.YEAR));
            }

            args[0] = cal;

        }
        setMethod.invoke(obj, args);

    } catch (Exception e) {
        DataBaseLoader.log_.error("saveData: " + method, e);
        throw new SAXException("saveData:", e);
    }

}

From source file:org.broadinstitute.gatk.queue.extensions.gatk.GATKExtensionsGenerator.java

/**
 * Writes the dependents to a scala wrapper that will compile and get picked up by BCEL.
 * BCEL was missing some classes, such as Enums, when they were defined in the other generated classes.
 * This generated wrapper makes sure they are explicitly seen by BCEL.
 * @param dependents Explicit dependencies that need to be packaged.
 * @throws IOException If the file cannot be written.
 *///w ww  .ja  v  a2 s .c  o m
private void writeDependencies(SortedSet<Class<?>> dependents) throws IOException {
    // Include the enclosing classes too.  Scala will be looking for them.
    SortedSet<Class<?>> enclosings = new TreeSet<Class<?>>(classComparator);
    for (Class<?> dependent : dependents)
        for (Class<?> enclosing = dependent; enclosing != null; enclosing = enclosing.getEnclosingClass())
            enclosings.add(enclosing);
    dependents = enclosings;

    // Oh, and include the classes defined on methods too!
    enclosings = new TreeSet<Class<?>>(classComparator);
    for (Class<?> dependent : dependents) {
        for (Method method : dependent.getDeclaredMethods()) {
            JVMUtils.addGenericTypes(enclosings, method.getGenericReturnType());
            for (Type parameterType : method.getGenericParameterTypes())
                JVMUtils.addGenericTypes(enclosings, parameterType);
            for (Type exceptionType : method.getGenericExceptionTypes())
                JVMUtils.addGenericTypes(enclosings, exceptionType);
        }
    }
    dependents = enclosings;

    // Generate the dependents.
    String className = "GATKClassDependencies";
    StringBuilder classes = new StringBuilder();

    for (Class<?> dependent : dependents) {
        if (dependent.isArray())
            continue;
        if (ArgumentField.isBuiltIn(dependent))
            continue;
        if (!Modifier.isPublic(dependent.getModifiers()))
            continue;
        if (classes.length() > 0)
            classes.append(",").append(NEWLINE);
        String typeParams = getScalaTypeParams(dependent);
        classes.append("classOf[").append(dependent.getName().replace("$", ".")).append(typeParams).append("]");
    }
    String content = String.format(GATK_DEPENDENCIES_TEMPLATE, GATK_EXTENSIONS_PACKAGE_NAME, className,
            classes);
    writeFile(GATK_EXTENSIONS_PACKAGE_NAME + "." + className, content);
}

From source file:org.openmrs.module.sync.SyncUtil.java

/**
 * This monstrosity looks for getter(s) on the parent object of an OpenmrsObject that return a
 * collection of the originally passed in OpenmrsObject type. This then explicitly removes the
 * object from the parent collection, and if the parent is a Patient or Person, calls save on
 * the parent./*from   w  w w. ja v a 2 s  .  c  om*/
 * 
 * @param item -- the OpenmrsObject to remove and save
 */
private static void removeFromPatientParentCollectionAndSave(OpenmrsObject item) {
    Field[] f = item.getClass().getDeclaredFields();
    for (int k = 0; k < f.length; k++) {
        Type fieldType = f[k].getGenericType();
        if (org.openmrs.OpenmrsObject.class.isAssignableFrom((Class) fieldType)) { //if the property is an OpenmrsObject (excludes lists, etc..)
            Method getter = getGetterMethod(item.getClass(), f[k].getName()); //get the getters
            OpenmrsObject parent = null; //the parent object
            if (getter == null) {
                continue; //no prob -- eliminates most utility methods on item
            }
            try {
                parent = (OpenmrsObject) getter.invoke(item, null); //get the parent object
            } catch (Exception ex) {
                log.debug(
                        "in removeFromParentCollection:  getter probably did not return an object that could be case as an OpenmrsObject",
                        ex);
            }
            if (parent != null) {
                Method[] methods = getter.getReturnType().getDeclaredMethods(); //get the Parent's methods to inspect
                for (Method method : methods) {
                    Type type = method.getGenericReturnType();
                    //return is a parameterizable and there are 0 arguments to method and the return is a Collection
                    if (ParameterizedType.class.isAssignableFrom(type.getClass())
                            && method.getGenericParameterTypes().length == 0
                            && method.getName().contains("get")) { //get the methods on Person that return Lists or Sets
                        ParameterizedType pt = (ParameterizedType) type;
                        for (int i = 0; i < pt.getActualTypeArguments().length; i++) {
                            Type t = pt.getActualTypeArguments()[i];
                            // if the return type matches the original object, and the return is not a Map
                            if (item.getClass().equals(t)
                                    && !pt.getRawType().toString().equals(java.util.Map.class.toString())
                                    && java.util.Collection.class.isAssignableFrom((Class) pt.getRawType())) {
                                try {
                                    Object colObj = (Object) method.invoke(parent, null); //get the list
                                    if (colObj != null) {
                                        java.util.Collection collection = (java.util.Collection) colObj;
                                        Iterator it = collection.iterator();
                                        boolean atLeastOneRemoved = false;
                                        while (it.hasNext()) {
                                            OpenmrsObject omrsobj = (OpenmrsObject) it.next();
                                            if (omrsobj.getUuid() != null
                                                    && omrsobj.getUuid().equals(item.getUuid())) { //compare uuid of original item with Collection contents
                                                it.remove();
                                                atLeastOneRemoved = true;
                                            }
                                            if (atLeastOneRemoved && (parent instanceof org.openmrs.Patient
                                                    || parent instanceof org.openmrs.Person)) {
                                                // this is commented out because deleting of patients fails if it is here.
                                                // we really should not need to call "save", that can only cause problems.
                                                // removing the object from the parent collection is the important part, which we're doing above
                                                //Context.getService(SyncService.class).saveOrUpdate(parent);
                                            }
                                        }
                                    }
                                } catch (Exception ex) {
                                    log.error("Failed to build new collection", ex);
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

From source file:com.cloudera.api.model.ApiModelTest.java

/**
 * Compares two objects by recursively comparing all of the fields that have
 * JAX-B annotations (@XmlElement and @XmlElementWrapper). This check assumes
 * that all getters are annotated and public, as is our convention.
 * <p/>/*www. j  a va 2s .  c  o  m*/
 * The test requires that all non-API-object properties of the instances
 * being compared are properly set. The assumption is that there is at least
 * one test for each API type (explicitly or implicitly through another
 * object's test), so that in the end everything is covered.
 */
private static void compareObjects(Object expected, Object deserialized) {
    try {
        for (Method m : expected.getClass().getMethods()) {
            String methodName = getMethodName(m);

            XmlElement elem = m.getAnnotation(XmlElement.class);
            if (elem != null) {
                compareChildObjects(m, m.getReturnType(), m.invoke(expected), m.invoke(deserialized));
                continue;
            }

            XmlElementWrapper wrapper = m.getAnnotation(XmlElementWrapper.class);
            if (wrapper != null) {
                assertTrue(Collection.class.isAssignableFrom(m.getReturnType()));
                assertTrue("Unexpected generic return in " + methodName,
                        m.getGenericReturnType() instanceof ParameterizedType);

                Type memberType = ((ParameterizedType) m.getGenericReturnType()).getActualTypeArguments()[0];
                assertTrue("Unexpected generic argument in " + methodName, memberType instanceof Class);

                Collection<?> expectedItems = (Collection<?>) m.invoke(expected);
                Collection<?> deserializedItems = (Collection<?>) m.invoke(deserialized);
                if (!isApiType((Class<?>) memberType)) {
                    assertNotNull("No expected items for getter " + m.getName(), expectedItems);
                }
                if (expectedItems != null) {
                    assertNotNull("No deserialized items for getter " + methodName, deserializedItems);
                    assertEquals("Mismatched item count in values for getter " + methodName,
                            expectedItems.size(), deserializedItems.size());

                    Iterator<?> ex = expectedItems.iterator();
                    Iterator<?> ds = deserializedItems.iterator();
                    while (ex.hasNext()) {
                        compareChildObjects(m, (Class<?>) memberType, ex.next(), ds.next());
                    }
                }
            }
        }
    } catch (Exception e) {
        throw Throwables.propagate(e);
    }
}

From source file:org.localmatters.serializer.util.ReflectionUtilsTest.java

/**
 * Test getting the type arguments for a type
 * @throws Exception When the test fails
 */// w  w  w  .j  a v  a2 s . c om
public void testGetTypeArgumentsForType() throws Exception {
    assertNull(ReflectionUtils.getTypeArgumentsForType(String.class));
    assertNull(ReflectionUtils.getTypeArgumentsForType(List.class));
    assertNull(ReflectionUtils.getTypeArgumentsForType(Map.class));

    Type[] types = ReflectionUtils.getTypeArgumentsForType(ParameterizedObject.class);
    assertNotNull(types);
    assertEquals(1, types.length);
    assertSame(String.class, types[0]);

    Class<?> cl = ObjectWithGenerics.class;

    Method method = cl.getMethod("getList", (Class<?>[]) null);
    types = ReflectionUtils.getTypeArgumentsForType(method.getGenericReturnType());
    assertNull(types);

    method = cl.getMethod("getListOfString", (Class<?>[]) null);
    types = ReflectionUtils.getTypeArgumentsForType(method.getGenericReturnType());
    assertNotNull(types);
    assertEquals(1, types.length);
    assertSame(String.class, types[0]);

    method = cl.getMethod("getListOfListOfString", (Class<?>[]) null);
    types = ReflectionUtils.getTypeArgumentsForType(method.getGenericReturnType());
    assertNotNull(types);
    assertEquals(1, types.length);
    assertTrue(types[0] instanceof ParameterizedType);
    ParameterizedType type = (ParameterizedType) types[0];
    assertSame(List.class, type.getRawType());
    types = ReflectionUtils.getTypeArgumentsForType(type);
    assertNotNull(types);
    assertEquals(1, types.length);
    assertSame(String.class, types[0]);

    method = cl.getMethod("getListOfParameterizedObject", (Class<?>[]) null);
    types = ReflectionUtils.getTypeArgumentsForType(method.getGenericReturnType());
    assertNotNull(types);
    assertEquals(1, types.length);
    assertTrue(types[0] instanceof Class<?>);
    Class<?> klass = (Class<?>) types[0];
    types = ReflectionUtils.getTypeArgumentsForType(klass);
    assertNotNull(types);
    assertEquals(1, types.length);
    assertSame(String.class, types[0]);

    method = cl.getMethod("getListOfMapOfStringAndList", (Class<?>[]) null);
    types = ReflectionUtils.getTypeArgumentsForType(method.getGenericReturnType());
    assertNotNull(types);
    assertEquals(1, types.length);
    assertTrue(types[0] instanceof ParameterizedType);
    type = (ParameterizedType) types[0];
    assertSame(Map.class, type.getRawType());
    types = ReflectionUtils.getTypeArgumentsForType(type);
    assertNotNull(types);
    assertEquals(2, types.length);
    assertSame(String.class, types[0]);
    assertSame(List.class, types[1]);

    method = cl.getMethod("getMap", (Class<?>[]) null);
    types = ReflectionUtils.getTypeArgumentsForType(method.getGenericReturnType());
    assertNotNull(types);
    assertEquals(2, types.length);
    assertFalse(types[0] instanceof Class<?>);
    assertFalse(types[0] instanceof ParameterizedType);
    assertFalse(types[1] instanceof Class<?>);
    assertFalse(types[1] instanceof ParameterizedType);

    method = cl.getMethod("getMapOfStringAndDouble", (Class<?>[]) null);
    types = ReflectionUtils.getTypeArgumentsForType(method.getGenericReturnType());
    assertNotNull(types);
    assertEquals(2, types.length);
    assertTrue(types[0] instanceof Class<?>);
    assertSame(String.class, types[0]);
    assertTrue(types[1] instanceof Class<?>);
    assertSame(Double.class, types[1]);

    method = cl.getMethod("getArray", (Class<?>[]) null);
    types = ReflectionUtils.getTypeArgumentsForType(method.getGenericReturnType());
    assertNotNull(types);
    assertEquals(1, types.length);
    assertTrue(types[0] instanceof Class<?>);
    assertSame(String.class, types[0]);
}

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.apache.axis2.jaxws.marshaller.impl.alt.DocLitWrappedMinimalMethodMarshaller.java

/**
 * Return ComponentType, might need to look at the GenericType
 * @param pd ParameterDesc or null if return
 * @param operationDesc OperationDescription
 * @param msrd MarshalServiceRuntimeDescription
 * @return/*from   ww w  .ja  va 2 s . c  om*/
 */
private static Class getComponentType(ParameterDescription pd, OperationDescription operationDesc,
        MarshalServiceRuntimeDescription msrd) {
    Class componentType = null;
    if (log.isDebugEnabled()) {
        log.debug("start getComponentType");
        log.debug(" ParameterDescription=" + pd);
    }

    // Determine if array, list, or other
    Class cls = null;
    if (pd == null) {
        cls = operationDesc.getResultActualType();
    } else {
        cls = pd.getParameterActualType();
    }

    if (cls != null) {
        if (cls.isArray()) {
            componentType = cls.getComponentType();
        } else if (List.class.isAssignableFrom(cls)) {
            if (log.isDebugEnabled()) {
                log.debug("Parameter is a List: " + cls);
            }
            Method method = msrd.getMethod(operationDesc);
            if (log.isDebugEnabled()) {
                log.debug("Method is: " + method);
            }
            Type genericType = null;
            if (pd == null) {
                genericType = method.getGenericReturnType();
            } else {
                ParameterDescription[] pds = operationDesc.getParameterDescriptions();
                for (int i = 0; i < pds.length; i++) {
                    if (pds[i] == pd) {
                        genericType = method.getGenericParameterTypes()[i];
                    }
                }
            }
            if (log.isDebugEnabled()) {
                log.debug("genericType is: " + genericType.getClass() + " " + genericType);
            }
            if (genericType instanceof Class) {
                if (log.isDebugEnabled()) {
                    log.debug(" genericType instanceof Class");
                }
                componentType = String.class;
            } else if (genericType instanceof ParameterizedType) {
                if (log.isDebugEnabled()) {
                    log.debug(" genericType instanceof ParameterizedType");
                }
                ParameterizedType pt = (ParameterizedType) genericType;
                if (pt.getRawType() == Holder.class) {
                    if (log.isDebugEnabled()) {
                        log.debug(" strip off holder");
                    }
                    genericType = pt.getActualTypeArguments()[0];
                    if (genericType instanceof Class) {
                        componentType = String.class;
                    } else if (genericType instanceof ParameterizedType) {
                        pt = (ParameterizedType) genericType;
                    }
                }
                if (componentType == null) {
                    Type comp = pt.getActualTypeArguments()[0];
                    if (log.isDebugEnabled()) {
                        log.debug(" comp =" + comp.getClass() + " " + comp);
                    }
                    if (comp instanceof Class) {
                        componentType = (Class) comp;
                    } else if (comp instanceof ParameterizedType) {
                        componentType = (Class) ((ParameterizedType) comp).getRawType();
                    }
                }
            }

        }
    }

    if (log.isDebugEnabled()) {
        log.debug("end getComponentType=" + componentType);
    }
    return componentType;
}