Java Code Examples for java.lang.reflect.Method.getGenericReturnType()

The following are Jave code examples for showing how to use getGenericReturnType() of the java.lang.reflect.Method class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: dubbox-hystrix   File: RpcUtils.java   View Source Code Vote up 6 votes
public static Type[] getReturnTypes(Invocation invocation) {
    try {
        if (invocation != null && invocation.getInvoker() != null
                && invocation.getInvoker().getUrl() != null
                && ! invocation.getMethodName().startsWith("$")) {
            String service = invocation.getInvoker().getUrl().getServiceInterface();
            if (service != null && service.length() > 0) {
                Class<?> cls = ReflectUtils.forName(service);
                Method method = cls.getMethod(invocation.getMethodName(), invocation.getParameterTypes());
                if (method.getReturnType() == void.class) {
                    return null;
                }
                return new Type[]{method.getReturnType(), method.getGenericReturnType()};
            }
        }
    } catch (Throwable t) {
        logger.warn(t.getMessage(), t);
    }
    return null;
}
 
Example 2
Project: stroom-query   File: ClassPhotographer.java   View Source Code Vote up 6 votes
/**
 * Looks at a method and gets any return or parameter types that match the basePackage.
 */
private static List<Class> getClassesForRecursion(String basePackage, Method method){
    List<Class> classesForRecursion = new ArrayList<>();

    // Check regular return types
    if (method.getReturnType().toString().contains(basePackage)) {
        classesForRecursion.add(method.getReturnType());
    } else {
        // Check for generic return types
        if (method.getGenericReturnType() instanceof ParameterizedType) {
            ParameterizedType type = (ParameterizedType) method.getGenericReturnType();
            Arrays.stream(type.getActualTypeArguments())
                    .filter(actualType -> actualType.getTypeName().contains(basePackage))
                    .forEach(actualType -> classesForRecursion.add((Class) actualType));
        }
    }

    // Check for parameter types
    Arrays.stream(method.getParameterTypes())
            .filter(paramType -> paramType.toString().contains(basePackage))
            .forEach(classesForRecursion::add);

    return classesForRecursion;
}
 
Example 3
Project: openjdk-jdk10   File: RuntimeModeler.java   View Source Code Vote up 6 votes
private Class getAsyncReturnType(Method method, Class returnType) {
    if(Response.class.isAssignableFrom(returnType)){
        Type ret = method.getGenericReturnType();
        return erasure(((ParameterizedType)ret).getActualTypeArguments()[0]);
    }else{
        Type[] types = method.getGenericParameterTypes();
        Class[] params = method.getParameterTypes();
        int i = 0;
        for(Class cls : params){
            if(AsyncHandler.class.isAssignableFrom(cls)){
                return erasure(((ParameterizedType)types[i]).getActualTypeArguments()[0]);
            }
            i++;
        }
    }
    return returnType;
}
 
Example 4
Project: OpenJSharp   File: RuntimeModeler.java   View Source Code Vote up 6 votes
private Class getAsyncReturnType(Method method, Class returnType) {
    if(Response.class.isAssignableFrom(returnType)){
        Type ret = method.getGenericReturnType();
        return (Class) Utils.REFLECTION_NAVIGATOR.erasure(((ParameterizedType)ret).getActualTypeArguments()[0]);
    }else{
        Type[] types = method.getGenericParameterTypes();
        Class[] params = method.getParameterTypes();
        int i = 0;
        for(Class cls : params){
            if(AsyncHandler.class.isAssignableFrom(cls)){
                return (Class) Utils.REFLECTION_NAVIGATOR.erasure(((ParameterizedType)types[i]).getActualTypeArguments()[0]);
            }
            i++;
        }
    }
    return returnType;
}
 
Example 5
Project: flow-platform   File: YmlAdaptor.java   View Source Code Vote up 5 votes
/**
 * get field type
 */
private Type getClazz(Field field, Class<?> clazz) {
    Method method = getGetterMethod(field, clazz);
    if (method == null) {
        return null;
    }

    return method.getGenericReturnType();
}
 
Example 6
Project: dubbox-hystrix   File: PojoUtilsTest.java   View Source Code Vote up 5 votes
public Type getType(String methodName){
    Method method;
    try {
        method = getClass().getDeclaredMethod(methodName, new Class<?>[]{} );
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }
    Type gtype = method.getGenericReturnType();
    return gtype;
}
 
Example 7
Project: GitHub   File: ASMUtilsTest.java   View Source Code Vote up 5 votes
public static Type getMethodType(Class<?> clazz, String methodName) {
    try {
        Method method = clazz.getMethod(methodName);

        return method.getGenericReturnType();
    } catch (Exception ex) {
        return null;
    }
}
 
Example 8
Project: pcloud-networking-java   File: RxCallAdapter.java   View Source Code Vote up 5 votes
@Override
public CallAdapter<?, ?> get(ApiComposer apiComposer, Method method) {
    Type returnType = method.getGenericReturnType();
    Class<?> rawType = Types.getRawType(returnType);
    boolean isSingle = rawType == Single.class;
    if (rawType != Observable.class && !isSingle) {
        return null;
    }

    Type observableType = getParameterUpperBound(0, returnType);

    return new RxCallAdapter(observableType);
}
 
Example 9
Project: OpenJSharp   File: Introspector.java   View Source Code Vote up 5 votes
/**
 * Adds the property descriptor to the list store.
 */
private void addPropertyDescriptor(PropertyDescriptor pd) {
    String propName = pd.getName();
    List<PropertyDescriptor> list = pdStore.get(propName);
    if (list == null) {
        list = new ArrayList<>();
        pdStore.put(propName, list);
    }
    if (this.beanClass != pd.getClass0()) {
        // replace existing property descriptor
        // only if we have types to resolve
        // in the context of this.beanClass
        Method read = pd.getReadMethod();
        Method write = pd.getWriteMethod();
        boolean cls = true;
        if (read != null) cls = cls && read.getGenericReturnType() instanceof Class;
        if (write != null) cls = cls && write.getGenericParameterTypes()[0] instanceof Class;
        if (pd instanceof IndexedPropertyDescriptor) {
            IndexedPropertyDescriptor ipd = (IndexedPropertyDescriptor) pd;
            Method readI = ipd.getIndexedReadMethod();
            Method writeI = ipd.getIndexedWriteMethod();
            if (readI != null) cls = cls && readI.getGenericReturnType() instanceof Class;
            if (writeI != null) cls = cls && writeI.getGenericParameterTypes()[1] instanceof Class;
            if (!cls) {
                pd = new IndexedPropertyDescriptor(ipd);
                pd.updateGenericsFor(this.beanClass);
            }
        }
        else if (!cls) {
            pd = new PropertyDescriptor(pd);
            pd.updateGenericsFor(this.beanClass);
        }
    }
    list.add(pd);
}
 
Example 10
Project: EatDubbo   File: PojoUtilsTest.java   View Source Code Vote up 5 votes
public Type getType(String methodName){
    Method method;
    try {
        method = getClass().getDeclaredMethod(methodName, new Class<?>[]{} );
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }
    Type gtype = method.getGenericReturnType();
    return gtype;
}
 
Example 11
Project: android-arch-mvvm   File: ModuleManager.java   View Source Code Vote up 5 votes
private static void checkReturnType(Method method1, Method method2) {
    Class<?> returnType;
    Type returnType1, returnType2;
    if (ModuleCall.class.equals(method1.getReturnType())) { // 异步回调的方法
        returnType = method2.getReturnType();
        if (returnType.equals(Observable.class) || returnType.equals(Single.class) || returnType.equals(Flowable.class) || returnType.equals(Maybe.class)) {

            returnType1 = method1.getGenericReturnType();
            returnType2 = method2.getGenericReturnType();

            if (returnType1 instanceof ParameterizedType && returnType2 instanceof ParameterizedType) { // 都带泛型
                // 检查泛型的类型是否一样
                if (!((ParameterizedType) returnType1).getActualTypeArguments()[0].equals(((ParameterizedType) returnType2).getActualTypeArguments()[0])) {
                    throw new IllegalArgumentException(method1.getName() + "方法的返回值类型的泛型的须一样");
                }
            } else if (!(returnType1 instanceof Class && returnType2 instanceof Class)) {
                throw new IllegalArgumentException(method1.getName() + "方法的返回值类型的泛型的须一样");
            }
        } else {
            throw new IllegalArgumentException(String.format("%s::%s的返回值类型必须是Observable,Single,Flowable,Maybe之一", method2.getDeclaringClass().getSimpleName(), method2.getName()));
        }
    } else {
        if (!method1.getGenericReturnType().equals(method2.getGenericReturnType())) { //同步调用的返回值必须一样
            throw new IllegalArgumentException(method1.getName() + "方法的返回值类型不一样");
        }
    }
}
 
Example 12
Project: Samurai   File: OrmContext.java   View Source Code Vote up 5 votes
/**
 * 获得实体类型(从方法的返回值中获取),用于BeanHandler映射
 * @param method
 * @return
 */
private Class<?> getBeanHandlerType(Method method) {
    if (List.class.isAssignableFrom(method.getReturnType())) {
        Type type = method.getGenericReturnType();
        String typeName = type.getTypeName().replaceAll(".+<(.+)>", "$1");
        return ClassUtil.loadClass(typeName);
    }
    return method.getReturnType();
}
 
Example 13
Project: dubbo2   File: PojoUtilsTest.java   View Source Code Vote up 5 votes
public Type getType(String methodName){
    Method method;
    try {
        method = getClass().getDeclaredMethod(methodName, new Class<?>[]{} );
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }
    Type gtype = method.getGenericReturnType();
    return gtype;
}
 
Example 14
Project: guava-mock   File: TypeTokenTest.java   View Source Code Vote up 5 votes
public void testToGenericType_staticMemberClass() throws Exception {
  Method getStaticAnonymousClassMethod =
      TypeTokenTest.class.getDeclaredMethod("getStaticAnonymousClass", Object.class);
  ParameterizedType javacReturnType =
      (ParameterizedType) getStaticAnonymousClassMethod.getGenericReturnType();

  ParameterizedType parameterizedType =
      (ParameterizedType) TypeToken.toGenericType(GenericClass.class).getType();
  assertThat(parameterizedType.getOwnerType()).isEqualTo(javacReturnType.getOwnerType());
}
 
Example 15
Project: jkes   File: ReflectionUtils.java   View Source Code Vote up 5 votes
/**
 * @param method {@link Method} object
 * @return the actual type parameters used in the source code. Return <strong>empty</strong> list if no parametrized type
 */
public static List<String> getReturnTypeParameters(Method method) {
    List<String> typeParameters = new ArrayList<>();

    Type type = method.getGenericReturnType();
    String typeName = type.getTypeName(); // ex: java.util.List<com.timeyang.search.entity.Person>, java.lang.Long
    Pattern p = Pattern.compile("<((\\S+\\.?),?\\s*)>");
    Matcher m = p.matcher(typeName);
    while (m.find()) {
        typeParameters.add(m.group(2));
    }

    return typeParameters;
}
 
Example 16
Project: openjdk-jdk10   File: DefaultMXBeanMappingFactory.java   View Source Code Vote up 4 votes
private MXBeanMapping makeCompositeMapping(Class<?> c,
                                           MXBeanMappingFactory factory)
        throws OpenDataException {

    // For historical reasons GcInfo implements CompositeData but we
    // shouldn't count its CompositeData.getCompositeType() field as
    // an item in the computed CompositeType.
    final boolean gcInfoHack =
        (c.getName().equals("com.sun.management.GcInfo") &&
            c.getClassLoader() == null);

    ReflectUtil.checkPackageAccess(c);
    final List<Method> methods =
            MBeanAnalyzer.eliminateCovariantMethods(Arrays.asList(c.getMethods()));
    final SortedMap<String,Method> getterMap = newSortedMap();

    /* Select public methods that look like "T getX()" or "boolean
       isX()", where T is not void and X is not the empty
       string.  Exclude "Class getClass()" inherited from Object.  */
    for (Method method : methods) {
        final String propertyName = propertyName(method);

        if (propertyName == null)
            continue;
        if (gcInfoHack && propertyName.equals("CompositeType"))
            continue;

        Method old =
            getterMap.put(decapitalize(propertyName),
                        method);
        if (old != null) {
            final String msg =
                "Class " + c.getName() + " has method name clash: " +
                old.getName() + ", " + method.getName();
            throw new OpenDataException(msg);
        }
    }

    final int nitems = getterMap.size();

    if (nitems == 0) {
        throw new OpenDataException("Can't map " + c.getName() +
                                    " to an open data type");
    }

    final Method[] getters = new Method[nitems];
    final String[] itemNames = new String[nitems];
    final OpenType<?>[] openTypes = new OpenType<?>[nitems];
    int i = 0;
    for (Map.Entry<String,Method> entry : getterMap.entrySet()) {
        itemNames[i] = entry.getKey();
        final Method getter = entry.getValue();
        getters[i] = getter;
        final Type retType = getter.getGenericReturnType();
        openTypes[i] = factory.mappingForType(retType, factory).getOpenType();
        i++;
    }

    CompositeType compositeType =
        new CompositeType(c.getName(),
                          c.getName(),
                          itemNames, // field names
                          itemNames, // field descriptions
                          openTypes);

    return new CompositeMapping(c,
                                compositeType,
                                itemNames,
                                getters,
                                factory);
}
 
Example 17
Project: openjdk-jdk10   File: StandardMBeanIntrospector.java   View Source Code Vote up 4 votes
@Override
Type getGenericReturnType(Method m) {
    return m.getGenericReturnType();
}
 
Example 18
Project: boohee_v5.6   File: FieldInfo.java   View Source Code Vote up 4 votes
public FieldInfo(String name, Method method, Field field, Class<?> clazz, Type type, int ordinal, int serialzeFeatures) {
    Class<?> fieldClass;
    Type fieldType;
    Type genericFieldType;
    this.ordinal = 0;
    this.getOnly = false;
    this.name = name;
    this.method = method;
    this.field = field;
    this.ordinal = ordinal;
    this.serialzeFeatures = serialzeFeatures;
    if (method != null) {
        TypeUtils.setAccessible(method);
    }
    if (field != null) {
        TypeUtils.setAccessible(field);
    }
    if (method != null) {
        if (method.getParameterTypes().length == 1) {
            fieldClass = method.getParameterTypes()[0];
            fieldType = method.getGenericParameterTypes()[0];
        } else {
            fieldClass = method.getReturnType();
            fieldType = method.getGenericReturnType();
            this.getOnly = true;
        }
        this.declaringClass = method.getDeclaringClass();
    } else {
        fieldClass = field.getType();
        fieldType = field.getGenericType();
        this.declaringClass = field.getDeclaringClass();
    }
    if (clazz != null && fieldClass == Object.class && (fieldType instanceof TypeVariable)) {
        genericFieldType = getInheritGenericType(clazz, (TypeVariable) fieldType);
        if (genericFieldType != null) {
            this.fieldClass = TypeUtils.getClass(genericFieldType);
            this.fieldType = genericFieldType;
            return;
        }
    }
    genericFieldType = getFieldType(clazz, type, fieldType);
    if (genericFieldType != fieldType) {
        if (genericFieldType instanceof ParameterizedType) {
            fieldClass = TypeUtils.getClass(genericFieldType);
        } else if (genericFieldType instanceof Class) {
            fieldClass = TypeUtils.getClass(genericFieldType);
        }
    }
    this.fieldType = genericFieldType;
    this.fieldClass = fieldClass;
}
 
Example 19
Project: OpenJSharp   File: StandardMBeanIntrospector.java   View Source Code Vote up 4 votes
@Override
Type getGenericReturnType(Method m) {
    return m.getGenericReturnType();
}
 
Example 20
Project: jdk8u-jdk   File: StandardMBeanIntrospector.java   View Source Code Vote up 4 votes
@Override
Type getGenericReturnType(Method m) {
    return m.getGenericReturnType();
}