List of usage examples for java.lang.reflect Method getGenericReturnType
public Type getGenericReturnType()
From source file:org.apache.servicecomb.swagger.engine.SwaggerEnvironment.java
public SwaggerConsumer createConsumer(Class<?> consumerIntf, Class<?> swaggerIntf) { SwaggerConsumer consumer = new SwaggerConsumer(); consumer.setConsumerIntf(consumerIntf); consumer.setSwaggerIntf(swaggerIntf); for (Method consumerMethod : consumerIntf.getMethods()) { String swaggerMethodName = findSwaggerMethodName(consumerMethod); // consumer??swagger? Method swaggerMethod = ReflectUtils.findMethod(swaggerIntf, swaggerMethodName); if (swaggerMethod == null) { // consumer method set bigger than contract, it's invalid // but we need to support consumer upgrade before producer, so only log and ignore it. LOGGER.warn("consumer method {}:{} not exist in contract.", consumerIntf.getName(), consumerMethod.getName()); continue; }/*w ww. j av a2 s. c o m*/ ArgumentsMapperConfig config = new ArgumentsMapperConfig(); config.setSwaggerMethod(swaggerMethod); config.setProviderMethod(consumerMethod); ConsumerArgumentsMapper argsMapper = consumerArgumentsFactory.createArgumentsMapper(config); ConsumerResponseMapper responseMapper = consumerResponseMapperFactorys.createResponseMapper( swaggerMethod.getGenericReturnType(), consumerMethod.getGenericReturnType()); SwaggerConsumerOperation op = new SwaggerConsumerOperation(); op.setName(consumerMethod.getName()); op.setConsumerMethod(consumerMethod); op.setSwaggerMethod(swaggerMethod); op.setArgumentsMapper(argsMapper); op.setResponseMapper(responseMapper); consumer.addOperation(op); } return consumer; }
From source file:com.igormaznitsa.upom.UPomModel.java
private boolean processPathStepToSet(final String[] path, final int pathStart, final Object instance, final Object value) throws Exception { final String fieldName = path[pathStart]; if (pathStart == path.length - 1) { // last step // find setter final Method setter = findMethod(instance.getClass(), "set" + fieldName, true); if (setter == null) { throw new UPomException("Can't find model field '" + makePathStr(path, pathStart) + '\''); }// ww w . j a v a2 s. c o m final Class[] params = setter.getParameterTypes(); if (params.length == 0) { throw new UPomException("Detected zero setter '" + makePathStr(path, pathStart) + "\'"); } else if (params.length == 1) { setter.invoke(instance, ensureCloning(value)); } else { final Field field = findDeclaredFieldForName(instance.getClass(), fieldName); if (field != null) { setField(instance, field, value); } else { throw new UPomException("Unsupported type for '" + makePathStr(path, pathStart) + "\'"); } } return true; } else { // find getter final Method getter = findMethod(instance.getClass(), "get" + fieldName, true); if (getter == null) { throw new UPomException("Can't find model field '" + makePathStr(path, pathStart) + '\''); } final Object nextInstance = getter.invoke(instance); if (nextInstance == null) { return false; } final boolean theNextPathItemIsLastOne = path.length - 1 == pathStart + 1; if (nextInstance instanceof Collection) { final Type returnType = getter.getGenericReturnType(); if (returnType instanceof ParameterizedType) { final ParameterizedType paramType = (ParameterizedType) returnType; final Type[] argTypes = paramType.getActualTypeArguments(); if (theNextPathItemIsLastOne) { if (value == null) { ((Collection) nextInstance).clear(); return true; } else if (value instanceof Collection) { ((Collection) nextInstance).clear(); for (final Object obj : ((Collection) value)) { ((Collection) nextInstance).add(obj); } return true; } else { ((Collection) nextInstance).clear(); return ((Collection) nextInstance).add(value); } } final String nextPathItem = path[pathStart + 1].toLowerCase(Locale.ENGLISH); if (argTypes[0].toString().toLowerCase(Locale.ENGLISH).endsWith(nextPathItem)) { boolean result = false; for (final Object collectionItem : (Collection) nextInstance) { result |= processPathStepToSet(path, pathStart + 2, collectionItem, value); } return result; } else { throw new UPomException( "Collection element type is not '" + makePathStr(path, pathStart + 1) + '\''); } } else { throw new UPomException("Can't find model field '" + makePathStr(path, pathStart) + '\''); } } else if (nextInstance instanceof Map) { final Map map = (Map) nextInstance; final String nextPathItem = path[pathStart + 1]; if (theNextPathItemIsLastOne) { if (value == null) { map.remove(nextPathItem); } else { map.put(nextPathItem, value); } return true; } else { return map.containsKey(nextPathItem) ? processPathStepToSet(path, pathStart + 2, map.get(nextPathItem), value) : false; } } else { return processPathStepToSet(path, pathStart + 1, nextInstance, value); } } }
From source file:plugins.PlayReader.java
protected Class<?> getSubResource(Method method) { final Class<?> rawType = method.getReturnType(); final Class<?> type; if (Class.class.equals(rawType)) { type = getClassArgument(method.getGenericReturnType()); if (type == null) { return null; }// w ww.j av a2s. c o m } else { type = rawType; } if (type.getAnnotation(Api.class) != null) { return type; } if (config.isScanAllResources()) { // For sub-resources that are not annotated with @Api, look for any HttpMethods. for (Method m : type.getMethods()) { if (extractOperationMethod(null, m, null) != null) { return type; } } } return null; }
From source file:org.apache.olingo.ext.proxy.utils.CoreUtils.java
@SuppressWarnings({ "unchecked" }) private static void populate(final EdmEnabledODataClient client, final EntityInvocationHandler typeHandler, final Object bean, final Class<?> typeRef, final Class<? extends Annotation> getterAnn, final Iterator<? extends ClientProperty> propItor) { if (bean != null) { while (propItor.hasNext()) { final ClientProperty property = propItor.next(); final Method getter = ClassUtils.findGetterByAnnotatedName(typeRef, getterAnn, property.getName()); if (getter == null) { LOG.warn("Could not find any property annotated as {} in {}", property.getName(), bean.getClass().getName()); } else { try { if (property.hasNullValue()) { setPropertyValue(bean, getter, null); } else if (property.hasPrimitiveValue()) { setPropertyValue(bean, getter, primitiveValueToObject(property.getPrimitiveValue(), getPropertyClass(typeRef, property.getName()))); } else if (property.hasComplexValue()) { final Object complex = Proxy.newProxyInstance( Thread.currentThread().getContextClassLoader(), new Class<?>[] { getter.getReturnType() }, ComplexInvocationHandler.getInstance(typeHandler, getter.getReturnType())); populate(client, typeHandler, complex, Property.class, property.getValue().asComplex().iterator()); setPropertyValue(bean, getter, complex); } else if (property.hasCollectionValue()) { final ParameterizedType collType = (ParameterizedType) getter.getGenericReturnType(); final Class<?> collItemClass = (Class<?>) collType.getActualTypeArguments()[0]; Collection<Object> collection = (Collection<Object>) getter.invoke(bean); if (collection == null) { collection = new ArrayList<Object>(); setPropertyValue(bean, getter, collection); }/*from ww w .j a va2s . c o m*/ final Iterator<ClientValue> collPropItor = property.getValue().asCollection() .iterator(); while (collPropItor.hasNext()) { final ClientValue value = collPropItor.next(); if (value.isPrimitive()) { collection.add(primitiveValueToObject(value.asPrimitive(), getPropertyClass(typeRef, property.getName()))); } else if (value.isComplex()) { final Object collItem = Proxy.newProxyInstance( Thread.currentThread().getContextClassLoader(), new Class<?>[] { collItemClass }, ComplexInvocationHandler.getInstance(typeHandler, collItemClass)); populate(client, typeHandler, collItem, Property.class, value.asComplex().iterator()); collection.add(collItem); } } } } catch (Exception e) { LOG.error("Could not set property {} on {}", getter, bean, e); } } } } }
From source file:com.github.reinert.jjschema.v1.PropertyWrapper.java
public PropertyWrapper(CustomSchemaWrapper ownerSchemaWrapper, Set<ManagedReference> managedReferences, Method method, Field field) { super(null);// ww w . j a va 2s . co m if (method == null) throw new RuntimeException("Error at " + ownerSchemaWrapper.getJavaType().getName() + ": Cannot instantiate a PropertyWrapper with a null method."); this.ownerSchemaWrapper = ownerSchemaWrapper; this.field = field; this.method = method; String relativeId; Class<?> propertyType = method.getReturnType(); Class<?> collectionType = null; final String propertiesStr = "/properties/"; String itemsStr = "/items"; if (Collection.class.isAssignableFrom(propertyType)) { collectionType = method.getReturnType(); ParameterizedType genericType = (ParameterizedType) method.getGenericReturnType(); propertyType = (Class<?>) genericType.getActualTypeArguments()[0]; relativeId = propertiesStr + getName() + itemsStr; } else { relativeId = propertiesStr + getName(); } processReference(propertyType); if (getAccessibleObject().getAnnotation(SchemaIgnore.class) != null) { this.schemaWrapper = new EmptySchemaWrapper(); } else if (getReferenceType() == ReferenceType.BACKWARD) { SchemaWrapper schemaWrapperLocal; String id = processId(method.getReturnType()); if (id != null) { schemaWrapperLocal = new RefSchemaWrapper(propertyType, id); ownerSchemaWrapper.pushReference(getManagedReference()); } else { if (ownerSchemaWrapper.pushReference(getManagedReference())) { String relativeId1 = ownerSchemaWrapper.getRelativeId(); if (relativeId1.endsWith(itemsStr)) { relativeId1 = relativeId1.substring(0, relativeId1.substring(0, relativeId1.length() - itemsStr.length()).lastIndexOf("/") - (propertiesStr.length() - 1)); } else { relativeId1 = relativeId1.substring(0, relativeId1.lastIndexOf("/") - (propertiesStr.length() - 1)); } schemaWrapperLocal = new RefSchemaWrapper(propertyType, relativeId1); } else schemaWrapperLocal = new EmptySchemaWrapper(); } if (schemaWrapperLocal.isRefWrapper() && collectionType != null) this.schemaWrapper = SchemaWrapperFactory .createArrayRefWrapper((RefSchemaWrapper) schemaWrapperLocal); else this.schemaWrapper = schemaWrapperLocal; } else if (ownerSchemaWrapper.getJavaType() == propertyType) { SchemaWrapper schemaWrapperLocal = new RefSchemaWrapper(propertyType, ownerSchemaWrapper.getRelativeId()); if (collectionType != null) { this.schemaWrapper = SchemaWrapperFactory .createArrayRefWrapper((RefSchemaWrapper) schemaWrapperLocal); } else { this.schemaWrapper = schemaWrapperLocal; } } else { if (getReferenceType() == ReferenceType.FORWARD) { ownerSchemaWrapper.pullReference(getManagedReference()); } String relativeId1 = ownerSchemaWrapper.getRelativeId() + relativeId; if (collectionType != null) { this.schemaWrapper = SchemaWrapperFactory.createArrayWrapper(collectionType, propertyType, managedReferences, relativeId1); } else { this.schemaWrapper = SchemaWrapperFactory.createWrapper(propertyType, managedReferences, relativeId1); } processAttributes(getNode(), getAccessibleObject()); processNullable(); } }
From source file:org.apache.sling.models.impl.ModelAdapterFactory.java
private RuntimeException setMethod(InjectableMethod injectableMethod, Map<Method, Object> methods, Object value) {//from w ww . java 2s.c o m Method method = injectableMethod.getMethod(); Result<Object> result = adaptIfNecessary(value, method.getReturnType(), method.getGenericReturnType()); if (result.wasSuccessful()) { methods.put(method, result.getValue()); return null; } else { return result.getThrowable(); } }
From source file:io.swagger.jaxrs.Reader.java
protected Class<?> getSubResourceWithJaxRsSubresourceLocatorSpecs(Method method) { final Class<?> rawType = method.getReturnType(); final Class<?> type; if (Class.class.equals(rawType)) { type = getClassArgument(method.getGenericReturnType()); if (type == null) { return null; }// w ww . j a v a 2 s . co m } else { type = rawType; } if (method.getAnnotation(javax.ws.rs.Path.class) != null) { if (extractOperationMethod(null, method, null) == null) { return type; } } return null; }
From source file:org.topazproject.otm.metadata.AnnotationClassMetaFactory.java
private void registerSubClassResolver(ClassDefinition def, final Method method) throws OtmException { if (!Modifier.isStatic(method.getModifiers()) || !Modifier.isPublic(method.getModifiers())) throw new OtmException("@SubClassResolver method '" + method + "' is not public and static"); Method resolve = org.topazproject.otm.SubClassResolver.class.getDeclaredMethods()[0]; assert resolve.getName().equals("resolve") : "unexpected method found in SubClassResolver: " + resolve; if (method.getGenericReturnType() != resolve.getGenericReturnType()) throw new OtmException( "@SubClassResolver method '" + method + "' does not return " + resolve.getGenericReturnType()); if (!Arrays.equals(method.getGenericParameterTypes(), resolve.getGenericParameterTypes())) throw new OtmException("@SubClassResolver method '" + method + "' has wrong signature - " + "required: " + Arrays.toString(resolve.getGenericParameterTypes())); sf.addSubClassResolver(def.getName(), new org.topazproject.otm.SubClassResolver() { public ClassMetadata resolve(ClassMetadata superEntity, EntityMode instantiatableIn, SessionFactory sf, Collection<String> typeUris, TripleStore.Result statements) { try { return (ClassMetadata) method.invoke(null, superEntity, instantiatableIn, sf, typeUris, statements);/* w w w. j a v a 2 s . c o m*/ } catch (Exception e) { if (e instanceof InvocationTargetException) { Throwable t = ((InvocationTargetException) e).getCause(); if (t instanceof RuntimeException) throw (RuntimeException) t; if (t instanceof Error) throw (Error) t; } throw new OtmException("Error invoking '" + method + "'", e); } } }); }
From source file:io.swagger.jaxrs.Reader.java
protected Class<?> getSubResource(Method method) { final Class<?> rawType = method.getReturnType(); final Class<?> type; if (Class.class.equals(rawType)) { type = getClassArgument(method.getGenericReturnType()); if (type == null) { return null; }//from w ww .jav a2s. c o m } else { type = rawType; } if (type.getAnnotation(Api.class) != null) { return type; } // For sub-resources that are not annotated with @Api, look for any HttpMethods. for (Method m : type.getMethods()) { if (extractOperationMethod(null, m, null) != null) { return type; } } return null; }
From source file:com.bstek.dorado.data.method.MethodAutoMatchingUtils.java
private static MethodDescriptor describMethodIfMatching(Method method, Type[] requiredTypes, Type[] exactTypes, Type[] optionalTypes, Type returnType) { Type[] argTypes = method.getGenericParameterTypes(); if (argTypes.length > (requiredTypes.length + exactTypes.length + optionalTypes.length)) { return null; }/*from w w w . jav a 2s . c o m*/ int[] argIndexs = new int[argTypes.length]; int[] argMatchingRates = new int[argTypes.length]; for (int i = 0; i < argIndexs.length; i++) { argIndexs[i] = -1; argMatchingRates[i] = 0; } Type[] requiredTypeArray = new Type[requiredTypes.length]; Type[] exactTypeArray = new Type[exactTypes.length]; Type[] optionalTypeArray = new Type[optionalTypes.length]; System.arraycopy(requiredTypes, 0, requiredTypeArray, 0, requiredTypes.length); System.arraycopy(exactTypes, 0, exactTypeArray, 0, exactTypes.length); System.arraycopy(optionalTypes, 0, optionalTypeArray, 0, optionalTypes.length); // if (returnType != null && !returnType.equals(IgnoreType.class)) { Type methodReturnType = method.getGenericReturnType(); if (isTypeAssignableFrom(returnType, methodReturnType) == 0) { methodReturnType = toNonPrimitiveClass(methodReturnType); if (isTypeAssignableFrom(returnType, methodReturnType) == 0) { return null; } } } // ? for (int i = 0; i < requiredTypeArray.length; i++) { Type requiredType = requiredTypeArray[i]; int matchingArg = -1; for (int j = 0; j < argTypes.length; j++) { Type argType = argTypes[j]; if (isTypeAssignableFrom(argType, requiredType) > 0) { if (matchingArg == -1) { matchingArg = j; } else { Type conflictType = argTypes[matchingArg]; if (argType.equals(conflictType)) { // ???? return null; } else if (isTypeAssignableFrom(conflictType, argType) > 0) { matchingArg = j; } } } } // ? if (matchingArg != -1) { argIndexs[matchingArg] = i; argMatchingRates[matchingArg] = 10; } else { return null; } } // ?? for (int i = 0; i < exactTypeArray.length; i++) { Type exactType = exactTypeArray[i]; int matchingArg = -1; for (int j = 0; j < argTypes.length; j++) { Type argType = argTypes[j]; if (isTypeAssignableFrom(exactType, argType) > 0) { if (matchingArg == -1) { matchingArg = j; } else { // ????? return null; } } } // ?? if (matchingArg != -1) { if (argMatchingRates[matchingArg] == 0) { argIndexs[matchingArg] = requiredTypeArray.length + i; argMatchingRates[matchingArg] = 9; } else { // ????? return null; } } } // ??? int conflictArg = -1, matchingRate = 1000; for (int i = 0; i < argTypes.length; i++) { if (argMatchingRates[i] == 0) { Type argType = argTypes[i]; for (int j = 0; j < optionalTypeArray.length; j++) { Type optionalType = optionalTypeArray[j]; if (optionalType != null) { int rate = isTypeAssignableFrom(argType, optionalType); if (rate == 0) { rate = isTypesCompatible(argType, optionalType); } if (rate > 0) { int originMatchingRate = argMatchingRates[i]; if (originMatchingRate == 0) { argIndexs[i] = requiredTypeArray.length + exactTypeArray.length + j; argMatchingRates[i] = rate; matchingRate += (rate * 2); } else if (conflictArg != -1) { // ???? return null; } else if (originMatchingRate > rate) { matchingRate -= (5 - (originMatchingRate - rate)); // } else if (rate > originMatchingRate) { argIndexs[i] = requiredTypeArray.length + exactTypeArray.length + j; argMatchingRates[i] = rate; matchingRate -= (5 - (rate - originMatchingRate)); // } else { // ???? argIndexs[i] = -1; conflictArg = i; matchingRate -= (argTypes.length * 10); } } } } if (argIndexs[i] != -1) { optionalTypeArray[argIndexs[i] - exactTypeArray.length - requiredTypeArray.length] = null; } } } // ???? if (conflictArg != -1) { Type argType = argTypes[conflictArg]; for (int i = 0; i < optionalTypeArray.length; i++) { Type optionalType = optionalTypeArray[i]; if (optionalType != null && isTypeAssignableFrom(argType, optionalType) > 0) { if (argIndexs[conflictArg] == -1) { argIndexs[conflictArg] = requiredTypeArray.length + i; } else { return null; } } } } int undetermine = 0, undetermineIndex = -1; for (int i = 0; i < argIndexs.length; i++) { if (argIndexs[i] == -1) { undetermine++; undetermineIndex = i; } } // ?????? if (undetermine == 1 && optionalTypes.length == 1) { Type argType = argTypes[undetermineIndex]; if (isSimpleType(argType) && isSimpleType(optionalTypes[0])) { argIndexs[undetermineIndex] = requiredTypeArray.length + exactTypeArray.length; undetermine = 0; matchingRate -= 200; } } if (undetermine > 0) { return null; } return new MethodDescriptor(method, argIndexs, matchingRate); }