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

The following examples show how to use java.lang.reflect.Method#getGenericReturnType() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: spring-openapi   File: OperationsTransformer.java    License: MIT License 6 votes vote down vote up
private List<Class<?>> getGenericParams(Method method) {
	if (method.getGenericReturnType() instanceof ParameterizedType) {
		Type[] typeArguments = ((ParameterizedType) method.getGenericReturnType()).getActualTypeArguments();
		if (typeArguments != null && typeArguments.length > 0) {
			Type typeArgument = typeArguments[0];
			if (typeArgument instanceof Class<?>) {
				return singletonList((Class<?>) typeArgument);
			} else if (typeArguments[0] instanceof ParameterizedType) {
				ParameterizedType parameterizedType = (ParameterizedType) typeArgument;
				Type[] innerGenericTypes = parameterizedType.getActualTypeArguments();
				return innerGenericTypes.length > 0 ?
					   asList(classForName(innerGenericTypes[0]), classForName(parameterizedType.getRawType())) :
					   null;
			}
		}
	}
	return null;
}
 
Example 2
Source Project: dubbo-2.6.5   File: RpcUtils.java    License: Apache License 2.0 6 votes vote down vote up
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 3
@Test public void When_Call_Adapt_Type_With_Single_Response_Mock_Then_Unwrap_Its_Value()
    throws NoSuchMethodException {
  Method method = Providers.class.getDeclaredMethod("singleResponseMock");

  Rx2Retrofit annotation = PlaceholderRetrofitAnnotation.class.getAnnotation(Rx2Retrofit.class);
  Metadata<Rx2Retrofit> metadata = new Metadata(Providers.class,
      method, null, annotation, method.getGenericReturnType());

  Type methodType = method.getGenericReturnType();
  Type expectedType = Mock.class;

  Type adaptedType = rx2RetrofitInterceptor
      .adaptType(methodType, metadata);

  assertEquals(expectedType, adaptedType);
}
 
Example 4
Source Project: turbo-rpc   File: ServerInvokerFactory.java    License: Apache License 2.0 5 votes vote down vote up
private void registerClassId(Method method) {
	if (method == null) {
		return;
	}

	Type returnType = method.getGenericReturnType();
	registerClassId(returnType);

	Type[] genericParameterTypes = method.getGenericParameterTypes();
	for (int i = 0; i < genericParameterTypes.length; i++) {
		registerClassId(genericParameterTypes[i]);
	}
}
 
Example 5
/**
 * Checks whether the given op implementation matches the specified method,
 * including op name, as well as input and output type parameters.
 * 
 * @param method The method to which the {@link Op} should be compared.
 * @param qName The fully qualified (with namespace) name of the op.
 * @param opType The {@link Op} to which the method should be compared.
 * @param coverSet The set of ops which have already matched a method.
 * @param checkTypes Whether to validate that the method's type arguments and
 *          return type match the given op implementation's types.
 * @return true iff the method and {@link Op} match up.
 */
private boolean checkOpImpl(final Method method, final String qName,
	final Class<? extends Op> opType, final OpCoverSet coverSet,
	final boolean checkTypes)
{
	// TODO: Type matching needs to be type<->type instead of class<->type.
	// That is, the "special class placeholder" also needs to work with Type.
	// Then we can pass Types here instead of Class instances.
	// final Object[] argTypes = method.getGenericParameterTypes();
	final Object[] argTypes = method.getParameterTypes();
	final OpInfo info = ops.info(opType);

	if (checkTypes) {
		final OpRef ref = OpRef.create(qName, argTypes);
		final OpCandidate candidate = new OpCandidate(ops, ref, info);

		// check input types
		if (!inputTypesMatch(candidate)) {
			error("Mismatched inputs", opType, method);
			return false;
		}

		// check output types
		final Type returnType = method.getGenericReturnType();
		if (!outputTypesMatch(returnType, candidate)) {
			error("Mismatched outputs", opType, method);
			return false;
		}
	}

	// mark this op as covered (w.r.t. the given number of args)
	coverSet.add(info, argTypes.length);

	return true;
}
 
Example 6
Source Project: Mockery   File: DTOArgsMockeryTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test public void When_Call_Legal_Then_Get_Legal()
    throws NoSuchMethodException {
  Method method = Providers.class.getDeclaredMethod("DTOArgs");
  DTOArgs annotation = method.getAnnotation(DTOArgs.class);
  Type type = method.getGenericReturnType();
  Object[] args = {DTOArgsPass.class.getName()};

  Metadata<DTOArgs> metadata = new Metadata<>(Providers.class,
      method, args, annotation, type);

  Mock mock = (Mock) dtoMockeryArgs.legal(metadata);
  assertThat(mock.s1, is(DTOArgsPass.class.getName()));
}
 
Example 7
@Test public void When_Call_Adapt_Type_With_Observable_List_Mock_Then_Unwrap_Its_Value() throws NoSuchMethodException {
  Method method = Providers.class.getDeclaredMethod("observableMocks");

  RxRetrofit annotation = PlaceholderRetrofitAnnotation.class.getAnnotation(RxRetrofit.class);
  Metadata<RxRetrofit> metadata = new Metadata(Providers.class,
      method, null, annotation, method.getGenericReturnType());

  Type methodType = method.getGenericReturnType();
  Type expectedType = Types.newParameterizedType(List.class, Mock.class);

  Type adaptedType = rxRetrofitInterceptor
      .adaptType(methodType, metadata);

  assertEquals(expectedType, adaptedType);
}
 
Example 8
Source Project: Jolyglot   File: JolyglotGenericsTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test public void jsonToMap() throws NoSuchMethodException {
  Method method = Types.class.getDeclaredMethod("mockMap");
  Type type = method.getGenericReturnType();

  Map<Integer, Mock> mocks = jolyglot.fromJson(jsonMockMapSample(), type);

  assertThat(jolyglot.toJson(mocks, type),
      is(jsonMockMapSample()));
}
 
Example 9
Source Project: Mockery   File: RetrofitInterceptorTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test public void When_Call_OnLegalMock_If_Method_Return_Type_Is_Not_Call_Parameterized_Then_Get_Exception()
    throws NoSuchMethodException {
  Method method = Providers.class.getDeclaredMethod("callNotParameterized");
  Retrofit annotation = PlaceholderRetrofitAnnotation.class.getAnnotation(Retrofit.class);
  Metadata<Retrofit> metadata = new Metadata(Providers.class,
      method, null, annotation, method.getGenericReturnType());

  exception.expect(RuntimeException.class);
  retrofitInterceptor.onLegalMock(new Mock(), metadata);
}
 
Example 10
Source Project: doov   File: ClassUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @param clazz container class
 * @param readRef read method reference
 * @param collected collected ordered map of container class to method
 * @return return type class
 */
private static Class extractMethod(Class clazz, ReadMethodRef<?, ?> readRef,
                LinkedHashMap<Class, Method> collected) {
    Method method = getReferencedMethod(clazz, readRef);
    collected.put(clazz, method);
    if (ParameterizedType.class.isAssignableFrom(method.getGenericReturnType().getClass())) {
        ParameterizedType parameterizedType = (ParameterizedType) method.getGenericReturnType();
        return (Class) parameterizedType.getActualTypeArguments()[0];
    } else {
        return method.getReturnType();
    }
}
 
Example 11
Source Project: faster-framework-project   File: Utils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 通过反射获取方法的返回参数的泛型
 *
 * @param method 方法
 * @return 泛型
 */
public static Type[] reflectMethodReturnTypes(Method method) {
    Type type = method.getGenericReturnType();
    if (type instanceof ParameterizedType) {
        return ((ParameterizedType) type).getActualTypeArguments();
    }
    return new Type[]{Object.class};
}
 
Example 12
private Type methodReturnType(Class<?> modelClass, String methodName) {
    Method[] methods = modelClass.getMethods();
    for (Method method : methods) {
        if (method.getName().equals(methodName)) return method.getGenericReturnType();
    }
    throw new Error(format("can not find method, class={}, method={}, expression={}, location={}", modelClass.getCanonicalName(), methodName, expressionSource, location));
}
 
Example 13
Source Project: onetwo   File: ReflectUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static Class getListGenricType(final Class clazz) {
	Class genClass = null;
	if (List.class.isAssignableFrom(clazz)) {
		Method method = findMethod(clazz, "get", int.class);
		if (method != null) {
			Type rtype = method.getGenericReturnType();
			if (ParameterizedType.class.isAssignableFrom(rtype.getClass())) {
				ParameterizedType ptype = (ParameterizedType) rtype;
				genClass = (Class) ptype.getActualTypeArguments()[0];
			}
		}
	}
	return genClass;
}
 
Example 14
Source Project: Firefly   File: FunctionCall.java    License: Apache License 2.0 5 votes vote down vote up
private Type getMethodReturnType(Method method) {
    Type type = method.getGenericReturnType();
    if (isObservable) {
        if (type instanceof ParameterizedType) {
            type = ((ParameterizedType) type).getActualTypeArguments()[0];
        } else {
            type = Object.class;
        }
    }
    return type;
}
 
Example 15
@Test
public void When_Call_OnIllegalMock_If_Method_Return_Type_Is_Not_Single_Or_Completable_Then_Get_Exception()
    throws NoSuchMethodException {
  Method method = Providers.class.getDeclaredMethod("mock");
  Rx2Retrofit annotation = PlaceholderRetrofitAnnotation.class.getAnnotation(Rx2Retrofit.class);
  Metadata<Rx2Retrofit> metadata = new Metadata(Providers.class,
      method, null, annotation, method.getGenericReturnType());

  exception.expect(RuntimeException.class);
  rx2RetrofitInterceptor.onIllegalMock(new AssertionError(), metadata);
}
 
Example 16
private String getReturnTypeSimpleName(final Method method) {
  try {
    ParameterizedType pt = (ParameterizedType) method.getGenericReturnType();
    Type t = pt.getActualTypeArguments()[0];
    return ((Class<?>) t).getSimpleName();
  } catch (ClassCastException e) {
    return method.getReturnType().getSimpleName();
  }
}
 
Example 17
@Test public void When_Call_Adapt_Type_With_Observable_Response_Mock_Then_Unwrap_Its_Value() throws NoSuchMethodException {
  Method method = Providers.class.getDeclaredMethod("observableResponseMock");

  RxRetrofit annotation = PlaceholderRetrofitAnnotation.class.getAnnotation(RxRetrofit.class);
  Metadata<RxRetrofit> metadata = new Metadata(Providers.class,
      method, null, annotation, method.getGenericReturnType());

  Type methodType = method.getGenericReturnType();
  Type expectedType = Mock.class;

  Type adaptedType = rxRetrofitInterceptor
      .adaptType(methodType, metadata);

  assertEquals(expectedType, adaptedType);
}
 
Example 18
static MethodInfo from(Method m,long luaFuncInfo,long nativePtr){
    Class returnType=m.getReturnType();
    return new MethodInfo(luaFuncInfo, generateParamTypes(m.getParameterTypes())
            , returnType,m.getGenericReturnType(),getClassType(nativePtr, returnType));
}
 
Example 19
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 20
Source Project: weed3   File: MethodWrap.java    License: Apache License 2.0 4 votes vote down vote up
protected MethodWrap(Method m) {
    method = m;
    parameters = m.getParameters();
    returnType = m.getReturnType();
    returnGenericType = m.getGenericReturnType();
}