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

The following examples show how to use java.lang.reflect.Method#getGenericReturnType() . 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 check out the related API usage on the sidebar.
Example 1
Source File: OperationsTransformer.java    From spring-openapi with 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 File: RpcUtils.java    From dubbo-2.6.5 with 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
Source File: Rx2RetrofitInterceptorTest.java    From Mockery with Apache License 2.0 6 votes vote down vote up
@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 File: RxRetrofitInterceptorTest.java    From Mockery with Apache License 2.0 5 votes vote down vote up
@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 5
Source File: ServerInvokerFactory.java    From turbo-rpc with 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 6
Source File: JPAEdmFunctionImport.java    From olingo-odata2 with Apache License 2.0 5 votes vote down vote up
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 7
Source File: Rx2RetrofitInterceptorTest.java    From Mockery with Apache License 2.0 5 votes vote down vote up
@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 8
Source File: FunctionCall.java    From Firefly with 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 9
Source File: ReflectUtils.java    From onetwo with 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 10
Source File: ExpressionBuilder.java    From core-ng-project with Apache License 2.0 5 votes vote down vote up
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 11
Source File: Utils.java    From faster-framework-project with 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
Source File: ClassUtils.java    From doov with 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 13
Source File: RetrofitInterceptorTest.java    From Mockery with 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 14
Source File: JolyglotGenericsTest.java    From Jolyglot with 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 15
Source File: RxRetrofitInterceptorTest.java    From Mockery with Apache License 2.0 5 votes vote down vote up
@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 16
Source File: DTOArgsMockeryTest.java    From Mockery with 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 17
Source File: AbstractNamespaceTest.java    From imagej-ops with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * 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 18
Source File: MethodWrap.java    From weed3 with 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();
}
 
Example 19
Source File: DefaultMXBeanMappingFactory.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
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 File: ScriptContext.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
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));
}