List of usage examples for java.lang.reflect Method getGenericReturnType
public Type getGenericReturnType()
From source file:de.escalon.hypermedia.spring.AffordanceBuilderFactory.java
private ActionDescriptor createActionDescriptor(Method invokedMethod, Map<String, Object> values, Object[] arguments) {// ww w .j a va 2 s . c o m RequestMethod httpMethod = getHttpMethod(invokedMethod); Type genericReturnType = invokedMethod.getGenericReturnType(); ActionDescriptor actionDescriptor = new ActionDescriptor(invokedMethod.getName(), httpMethod.name()); actionDescriptor.setCardinality(getCardinality(invokedMethod, httpMethod, genericReturnType)); final Action actionAnnotation = AnnotationUtils.getAnnotation(invokedMethod, Action.class); if (actionAnnotation != null) { actionDescriptor.setSemanticActionType(actionAnnotation.value()); } Map<String, ActionInputParameter> requestBodyMap = getActionInputParameters(RequestBody.class, invokedMethod, arguments); Assert.state(requestBodyMap.size() < 2, "found more than one request body on " + invokedMethod.getName()); for (ActionInputParameter value : requestBodyMap.values()) { actionDescriptor.setRequestBody(value); } // the action descriptor needs to know the param type, value and name Map<String, ActionInputParameter> requestParamMap = getActionInputParameters(RequestParam.class, invokedMethod, arguments); for (Map.Entry<String, ActionInputParameter> entry : requestParamMap.entrySet()) { ActionInputParameter value = entry.getValue(); if (value != null) { final String key = entry.getKey(); actionDescriptor.addRequestParam(key, value); if (!value.isRequestBody()) { values.put(key, value.getCallValueFormatted()); } } } Map<String, ActionInputParameter> pathVariableMap = getActionInputParameters(PathVariable.class, invokedMethod, arguments); for (Map.Entry<String, ActionInputParameter> entry : pathVariableMap.entrySet()) { ActionInputParameter actionInputParameter = entry.getValue(); if (actionInputParameter != null) { final String key = entry.getKey(); actionDescriptor.addPathVariable(key, actionInputParameter); if (!actionInputParameter.isRequestBody()) { values.put(key, actionInputParameter.getCallValueFormatted()); } } } Map<String, ActionInputParameter> requestHeadersMap = getActionInputParameters(RequestHeader.class, invokedMethod, arguments); for (Map.Entry<String, ActionInputParameter> entry : pathVariableMap.entrySet()) { ActionInputParameter actionInputParameter = entry.getValue(); if (actionInputParameter != null) { final String key = entry.getKey(); actionDescriptor.addRequestHeader(key, actionInputParameter); if (!actionInputParameter.isRequestBody()) { values.put(key, actionInputParameter.getCallValueFormatted()); } } } return actionDescriptor; }
From source file:com.strandls.alchemy.rest.client.stubgenerator.ServiceStubGenerator.java
/** * Add a rest method to the parent class. * * @param jCodeModel/*from www .ja v a 2s. c om*/ * the code model. * @param jParentClass * the parent class. * @param method * the method. * @param methodMetaData * the method metadata. */ private void addMethod(final JCodeModel jCodeModel, final JDefinedClass jParentClass, final Method method, final RestMethodMetadata methodMetaData) { final String mehtodName = method.getName(); final JType result = typeToJType(method.getReturnType(), method.getGenericReturnType(), jCodeModel); final JMethod jMethod = jParentClass.method(JMod.PUBLIC, result, mehtodName); @SuppressWarnings("unchecked") final Class<? extends Throwable>[] exceptionTypes = (Class<? extends Throwable>[]) method .getExceptionTypes(); for (final Class<? extends Throwable> exceptionCType : exceptionTypes) { jMethod._throws(exceptionCType); } addSingleValueAnnotation(jMethod, Path.class, ANNOTATION_VALUE_PARAM_NAME, methodMetaData.getPath()); addListAnnotation(jMethod, Produces.class, ANNOTATION_VALUE_PARAM_NAME, methodMetaData.getProduced()); addListAnnotation(jMethod, Consumes.class, ANNOTATION_VALUE_PARAM_NAME, methodMetaData.getConsumed()); final String httpMethod = methodMetaData.getHttpMethod(); Class<? extends Annotation> httpMethodAnnotation = null; if (HttpMethod.GET.equals(httpMethod)) { httpMethodAnnotation = GET.class; } else if (HttpMethod.PUT.equals(httpMethod)) { httpMethodAnnotation = PUT.class; } else if (HttpMethod.POST.equals(httpMethod)) { httpMethodAnnotation = POST.class; } else if (HttpMethod.DELETE.equals(httpMethod)) { httpMethodAnnotation = DELETE.class; } addAnnotation(jMethod, httpMethodAnnotation); final Annotation[][] parameterAnnotations = methodMetaData.getParameterAnnotations(); final Type[] argumentTypes = method.getGenericParameterTypes(); final Class<?>[] argumentClasses = method.getParameterTypes(); for (int i = 0; i < argumentTypes.length; i++) { final JType jType = typeToJType(argumentClasses[i], argumentTypes[i], jCodeModel); // we have lost the actual names, use generic arg names final String name = "arg" + i; final JVar param = jMethod.param(jType, name); if (parameterAnnotations.length > i) { for (final Annotation annotation : parameterAnnotations[i]) { final JAnnotationUse jAnnotation = param.annotate(annotation.annotationType()); final String value = getValue(annotation); if (value != null) { jAnnotation.param(ANNOTATION_VALUE_PARAM_NAME, value); } } } } }
From source file:com.netflix.hystrix.contrib.javanica.utils.FallbackMethod.java
public void validateReturnType(Method commandMethod) { if (isPresent()) { Class<?> commandReturnType = commandMethod.getReturnType(); if (ExecutionType.OBSERVABLE == ExecutionType.getExecutionType(commandReturnType)) { if (ExecutionType.OBSERVABLE != getExecutionType()) { Type commandParametrizedType = commandMethod.getGenericReturnType(); if (isReturnTypeParametrized(commandMethod)) { commandParametrizedType = getFirstParametrizedType(commandMethod); }/*from w ww . j a v a 2s . com*/ validateParametrizedType(commandParametrizedType, method.getGenericReturnType(), commandMethod, method); } else { validateReturnType(commandMethod, method); } } else if (ExecutionType.ASYNCHRONOUS == ExecutionType.getExecutionType(commandReturnType)) { if (isCommand() && ExecutionType.ASYNCHRONOUS == getExecutionType()) { validateReturnType(commandMethod, method); } if (ExecutionType.ASYNCHRONOUS != getExecutionType()) { Type commandParametrizedType = commandMethod.getGenericReturnType(); if (isReturnTypeParametrized(commandMethod)) { commandParametrizedType = getFirstParametrizedType(commandMethod); } validateParametrizedType(commandParametrizedType, method.getGenericReturnType(), commandMethod, method); } if (!isCommand() && ExecutionType.ASYNCHRONOUS == getExecutionType()) { throw new FallbackDefinitionException(createErrorMsg(commandMethod, method, "fallback cannot return Future if the fallback isn't command when the command is async.")); } } else { if (ExecutionType.ASYNCHRONOUS == getExecutionType()) { throw new FallbackDefinitionException(createErrorMsg(commandMethod, method, "fallback cannot return Future if command isn't asynchronous.")); } if (ExecutionType.OBSERVABLE == getExecutionType()) { throw new FallbackDefinitionException(createErrorMsg(commandMethod, method, "fallback cannot return Observable if command isn't observable.")); } validateReturnType(commandMethod, method); } } }
From source file:com.ewcms.common.query.mongo.PropertyConvert.java
/** * ?{@link RuntimeException}/*w w w . ja v a 2 s . c o m*/ * * @param name ???{@literal null} * @return {@value Class<?>} */ public Class<?> getPropertyType(String propertyName) { if (!StringUtils.hasText(propertyName)) { throw new IllegalArgumentException("Property's name must not null or empty!"); } String[] names = StringUtils.tokenizeToStringArray(propertyName, NESTED); Class<?> type = beanClass; PropertyDescriptor pd = null; for (String name : names) { pd = BeanUtils.getPropertyDescriptor(type, name); if (pd == null) { logger.error("\"{}\" property isn't exist.", propertyName); throw new RuntimeException(propertyName + " property isn't exist."); } type = pd.getPropertyType(); } if (type.isArray()) { return type.getComponentType(); } if (Collection.class.isAssignableFrom(type)) { Method method = pd.getReadMethod(); if (method == null) { logger.error("\"{}\" property is not read method.", propertyName); throw new RuntimeException(propertyName + " property is not read method."); } ParameterizedType returnType = (ParameterizedType) method.getGenericReturnType(); if (returnType.getActualTypeArguments().length > 0) { return (Class<?>) returnType.getActualTypeArguments()[0]; } logger.error("\"{}\" property is collection,but it's not generic.", propertyName); throw new RuntimeException(propertyName + " property is collection,but it's not generic."); } return type; }
From source file:org.springframework.hateoas.Jackson2PagedResourcesIntegrationTest.java
/** * @see SPR-13318/*from w w w .j a va 2s . c o m*/ */ @Test public void serializesPagedResourcesCorrectly() throws Exception { Assume.assumeThat(SPRING_4_2_WRITE_METHOD, is(notNullValue())); User user = new User(); user.firstname = "Dave"; user.lastname = "Matthews"; PageMetadata metadata = new PagedResources.PageMetadata(1, 0, 2); PagedResources<User> resources = new PagedResources<User>(Collections.singleton(user), metadata); Method method = Sample.class.getMethod("someMethod"); StringWriter writer = new StringWriter(); HttpOutputMessage outputMessage = mock(HttpOutputMessage.class); when(outputMessage.getBody()).thenReturn(new WriterOutputStream(writer)); when(outputMessage.getHeaders()).thenReturn(new HttpHeaders()); MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(); ReflectionUtils.invokeMethod(SPRING_4_2_WRITE_METHOD, converter, resources, method.getGenericReturnType(), MediaType.APPLICATION_JSON, outputMessage); assertThat(writer.toString(), is(REFERENCE)); }
From source file:org.apache.openejb.util.proxy.QueryProxy.java
private Class<?> getReturnedType(final Method method) { final String methodName = method.getName(); final Class<?> type; if (returnsTypes.containsKey(methodName)) { type = returnsTypes.get(methodName); } else {/*from ww w . ja v a2 s.c o m*/ type = getGenericType(method.getGenericReturnType()); returnsTypes.put(methodName, type); } return type; }
From source file:org.projectforge.continuousdb.TableAttribute.java
/** * @param method// w w w . j av a 2 s. co m * @return */ private void setGenericReturnType(final Method method) { Type returnType = method.getGenericReturnType(); if ((returnType instanceof ParameterizedType) == false) { return; } final ParameterizedType type = (ParameterizedType) returnType; OneToMany oneToMany = method.getAnnotation(OneToMany.class); if (oneToMany != null && oneToMany.targetEntity() != null && oneToMany.targetEntity() != Void.TYPE) { if (type.getRawType() instanceof Class) { if (List.class.isAssignableFrom((Class) type.getRawType()) == true) { genericType = oneToMany.targetEntity(); return; } } } final Type[] typeArguments = type.getActualTypeArguments(); if (typeArguments.length == 0) { return; } if (typeArguments[0] instanceof ParameterizedType) { final ParameterizedType nt = (ParameterizedType) typeArguments[0]; final Type[] nst = nt.getActualTypeArguments(); if (nst.length > 0) { final Class<?> typeArgClass = (Class<?>) nst[0]; if (log.isDebugEnabled() == true) { log.debug("Generic type found for '" + entityClass + "." + property + "': '" + typeArgClass + "'."); } genericType = typeArgClass; } } if ((typeArguments[0] instanceof Class) == false) { // opps final Class<?> thclas = typeArguments[0].getClass(); log.error("Cannot determine entity type: " + thclas.getName() + " in method: " + method); } else { final Class<?> typeArgClass = (Class<?>) typeArguments[0]; if (log.isDebugEnabled() == true) { log.debug("Generic type found for '" + entityClass + "." + property + "': '" + typeArgClass + "'."); } genericType = typeArgClass; } }
From source file:Main.java
public static void dumpMethod(final Method method) { final StringBuilder builder = new StringBuilder(); builder.append("------------------------------\n"); builder.append("MethodName: ").append(method.getName()).append("\n"); builder.append("ParameterTypes:{"); for (Class<?> cls : method.getParameterTypes()) { builder.append(cls.getName()).append(", "); }//from ww w . j a v a2s .c o m builder.append("}\n"); builder.append("GenericParameterTypes:{"); for (Type cls : method.getGenericParameterTypes()) { builder.append(cls.getClass()).append(", "); } builder.append("}\n"); builder.append("TypeParameters:{"); for (TypeVariable<Method> cls : method.getTypeParameters()) { builder.append(cls.getName()).append(", "); } builder.append("}\n"); builder.append("DeclaredAnnotations:{"); for (Annotation cls : method.getDeclaredAnnotations()) { builder.append(cls).append(", "); } builder.append("}\n"); builder.append("Annotations:{"); for (Annotation cls : method.getAnnotations()) { builder.append(cls).append(", "); } builder.append("}\n"); builder.append("ExceptionTypes:{"); for (Class<?> cls : method.getExceptionTypes()) { builder.append(cls.getName()).append(", "); ; } builder.append("}\n"); builder.append("ReturnType: ").append(method.getReturnType()); builder.append("\nGenericReturnType: ").append(method.getGenericReturnType()); builder.append("\nDeclaringClass: ").append(method.getDeclaringClass()); builder.append("\n"); System.out.println(builder.toString()); }
From source file:org.kuali.rice.krad.datadictionary.parse.CustomTagAnnotations.java
/** * Creates a map of entries the properties marked by the annotation of the bean class. * * @param tagClass class being mapped for attributes * @return Return a map of the properties found in the class with there associated information. *//*from w ww . j a v a 2 s.co m*/ public static Map<String, BeanTagAttributeInfo> getAttributes(Class<?> tagClass) { Map<String, BeanTagAttributeInfo> entries = new HashMap<String, BeanTagAttributeInfo>(); // search the methods of the class using reflection for the attribute annotation Method methods[] = tagClass.getMethods(); for (Method attributeMethod : methods) { BeanTagAttribute attribute = attributeMethod.getAnnotation(BeanTagAttribute.class); if (attribute == null) { continue; } BeanTagAttributeInfo info = new BeanTagAttributeInfo(); String propertyName = getFieldName(attributeMethod.getName()); info.setPropertyName(propertyName); if (StringUtils.isBlank(attribute.name())) { info.setName(propertyName); } else { info.setName(attribute.name()); } if (BeanTagAttribute.AttributeType.NOTSET.equals(attribute.type())) { BeanTagAttribute.AttributeType derivedType = deriveTypeFromMethod(attributeMethod); if (derivedType != null) { info.setType(derivedType); } } else { info.setType(attribute.type()); } info.setValueType(attributeMethod.getReturnType()); info.setGenericType(attributeMethod.getGenericReturnType()); validateBeanAttributes(tagClass.getName(), attribute.name(), entries); entries.put(info.getName(), info); } return entries; }
From source file:com.sulacosoft.bitcoindconnector4j.BitcoindApiHandler.java
private Object deserializeResult(Method method, Object result) { if (result instanceof MorphDynaBean) { return JSONObject.toBean(JSONObject.fromObject(JSONSerializer.toJSON((MorphDynaBean) result)), method.getReturnType()); } else if (result instanceof List) { List<?> incomingList = (List<?>) result; if (incomingList.size() == 0) return Collections.EMPTY_LIST; ParameterizedType type = (ParameterizedType) method.getGenericReturnType(); // method.getGenericType(); Class<?> clazz = (Class<?>) type.getActualTypeArguments()[0]; ArrayList<Object> outcomingList = new ArrayList<>(); if (incomingList.get(0) instanceof MorphDynaBean) { for (Object entity : incomingList) { Object ent = JSONObject.toBean(JSONObject.fromObject(entity), clazz); outcomingList.add(ent);//from www. jav a 2s .c o m } } else { outcomingList.addAll(incomingList); } return outcomingList; } else { return result; } }