List of usage examples for java.lang.reflect Method getGenericParameterTypes
@Override
public Type[] getGenericParameterTypes()
From source file:org.castor.jaxb.reflection.ClassInfoBuilder.java
/** * Build the FieldInfo for a Method./* w ww .j a v a 2 s.com*/ * * @param classInfo * the ClassInfo to look in if this field already exists * @param method * the Method to describe * @return the ClassInfo containing the FieldInfo build */ private void buildFieldInfo(final ClassInfo classInfo, final Method method) { if (classInfo == null) { String message = "Argument classInfo must not be null."; LOG.warn(message); throw new IllegalArgumentException(message); } if (method == null) { String message = "Argument method must not be null."; LOG.warn(message); throw new IllegalArgumentException(message); } String fieldName = javaNaming.extractFieldNameFromMethod(method); FieldInfo fieldInfo = classInfo.getFieldInfo(fieldName); if (fieldInfo == null) { fieldInfo = createFieldInfo(fieldName); classInfo.addFieldInfo(fieldInfo); fieldInfo.setParentClassInfo(classInfo); } JaxbFieldNature jaxbFieldNature = new JaxbFieldNature(fieldInfo); if (javaNaming.isAddMethod(method)) { jaxbFieldNature.setMethodAdd(method); jaxbFieldNature.setMultivalued(true); } else if (javaNaming.isCreateMethod(method)) { jaxbFieldNature.setMethodCreate(method); } else if (javaNaming.isGetMethod(method)) { jaxbFieldNature.setMethodGet(method); handleMultivaluedness(method.getReturnType(), jaxbFieldNature, method.getGenericReturnType()); } else if (javaNaming.isSetMethod(method)) { jaxbFieldNature.setMethodSet(method); Class<?>[] parameterTypes = method.getParameterTypes(); if (parameterTypes.length == 1) { handleMultivaluedness(parameterTypes[0], jaxbFieldNature, method.getGenericParameterTypes()[0]); } } else if (javaNaming.isIsMethod(method)) { jaxbFieldNature.setMethodIs(method); } else { if (LOG.isDebugEnabled()) { String message = "Method: " + method + " is of unsupported type and ignored."; LOG.debug(message); } } fieldAnnotationProcessingService.processAnnotations(jaxbFieldNature, method.getAnnotations()); }
From source file:net.firejack.platform.model.service.reverse.ReverseEngineeringService.java
private EntityModel createWrapperEntity(String name, Method method, RegistryNodeModel registryNodeModel, boolean request, List<RelationshipModel> relationships, Map<String, EntityModel> models, Service service) {//ww w .j a v a 2 s. c o m EntityModel model = models.get(name); if (model != null) return model; String modelName = name.replaceAll("\\B([A-Z]+)\\B", " $1"); EntityModel entityModel = new EntityModel(); entityModel.setName(modelName); entityModel.setLookup(DiffUtils.lookup(registryNodeModel.getLookup(), modelName)); entityModel.setPath(registryNodeModel.getLookup()); entityModel.setAbstractEntity(false); entityModel.setTypeEntity(true); entityModel.setReverseEngineer(true); entityModel.setProtocol(EntityProtocol.HTTP); entityModel.setParent(registryNodeModel); models.put(name, entityModel); Annotation[][] parameterAnnotations = method.getParameterAnnotations(); Type[] parameterTypes = method.getGenericParameterTypes(); List<FieldModel> fields = new ArrayList<FieldModel>(parameterTypes.length); for (int i = 0; i < parameterTypes.length; i++) { Annotation[] annotations = parameterAnnotations[i]; for (Annotation annotation : annotations) { if (WebParam.class.isInstance(annotation)) { WebParam param = (WebParam) annotation; if (param.mode() == INOUT || request && param.mode() == IN || !request && param.mode() == OUT) { analyzeField(param.name(), parameterTypes[i], TYPE, entityModel, null, models, relationships, fields); analyzeField(param.name(), parameterTypes[i], param.mode(), false, false, false, service); } break; } } } Type returnType = method.getGenericReturnType(); if (!request && void.class != returnType) { analyzeField(RETURN, returnType, TYPE, entityModel, null, models, relationships, fields); analyzeField(RETURN, returnType, null, false, false, true, service); } entityModel.setFields(fields); return entityModel; }
From source file:org.eclipse.wb.tests.designer.core.util.reflect.ReflectionUtilsTest.java
public void test_getFullyQualifiedName_TypeVariable() throws Exception { @SuppressWarnings("unused") class Foo {//from ww w. j av a 2 s.c o m <T> void foo(T values) { } } Method method = Foo.class.getDeclaredMethods()[0]; String expected = "T"; check_getFullyQualifiedName(expected, expected, method.getGenericParameterTypes()[0]); }
From source file:org.eclipse.wb.tests.designer.core.util.reflect.ReflectionUtilsTest.java
public void test_getFullyQualifiedName_GenericArrayType() throws Exception { @SuppressWarnings("unused") class Foo {//from w w w .j av a2 s .c o m <T> void foo(T[] values) { } } Method method = Foo.class.getDeclaredMethods()[0]; String expected = "T[]"; check_getFullyQualifiedName(expected, expected, method.getGenericParameterTypes()[0]); }
From source file:com.strandls.alchemy.rest.client.stubgenerator.ServiceStubGenerator.java
/** * Add a rest method to the parent class. * * @param jCodeModel/*from ww w .jav a 2 s. co m*/ * 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:org.eclipse.wb.tests.designer.core.util.reflect.ReflectionUtilsTest.java
public void test_getFullyQualifiedName_ParameterizedType() throws Exception { @SuppressWarnings("unused") class Foo {//from w ww . ja va 2 s . com <K, V> void foo(Map<K, V> values) { } } Method method = Foo.class.getDeclaredMethods()[0]; String expected = "java.util.Map<K,V>"; check_getFullyQualifiedName(expected, expected, method.getGenericParameterTypes()[0]); }
From source file:org.eclipse.wb.tests.designer.core.util.reflect.ReflectionUtilsTest.java
public void test_getFullyQualifiedName_WildcardType() throws Exception { @SuppressWarnings("unused") class Foo {/* ww w .java 2s . c o m*/ <T> void foo(List<? extends T> values) { } } Method method = Foo.class.getDeclaredMethods()[0]; String expected = "java.util.List<? extends T>"; check_getFullyQualifiedName(expected, expected, method.getGenericParameterTypes()[0]); }
From source file:de.pribluda.android.jsonmarshaller.JSONUnmarshaller.java
/** * TODO: provide support for nested JSON objects * TODO: provide support for embedded JSON Arrays * * @param jsonObject/* w w w. j a v a 2 s . co m*/ * @param beanToBeCreatedClass * @param <T> * @return * @throws IllegalAccessException * @throws InstantiationException * @throws JSONException * @throws NoSuchMethodException * @throws java.lang.reflect.InvocationTargetException */ @SuppressWarnings({ "unchecked", "rawtypes" }) public static <T> T unmarshall(JSONObject jsonObject, Class<T> beanToBeCreatedClass) throws IllegalAccessException, InstantiationException, JSONException, NoSuchMethodException, InvocationTargetException { T value = beanToBeCreatedClass.getConstructor().newInstance(); Iterator keys = jsonObject.keys(); while (keys.hasNext()) { String key = (String) keys.next(); Object field = jsonObject.get(key); // capitalise to standard setter pattern String methodName = SETTER_PREFIX + key.substring(0, 1).toUpperCase() + key.substring(1); //System.err.println("method name:" + methodName); Method method = getCandidateMethod(beanToBeCreatedClass, methodName); if (method != null) { Class clazz = method.getParameterTypes()[0]; // discriminate based on type if (field.equals(JSONObject.NULL)) { method.invoke(value, clazz.cast(null)); } else if (field instanceof String) { // check if we're an enum if (clazz.isEnum()) { Object enm = clazz.getMethod("valueOf", String.class).invoke(null, field); try { beanToBeCreatedClass.getMethod(methodName, clazz).invoke(value, enm); continue; } catch (NoSuchMethodException e) { // that means there was no such method, proceed } } // string shall be used directly, either to set or as constructor parameter (if suitable) try { beanToBeCreatedClass.getMethod(methodName, String.class).invoke(value, field); continue; } catch (NoSuchMethodException e) { // that means there was no such method, proceed } // or maybe there is method with suitable parameter? if (clazz.isPrimitive() && primitves.get(clazz) != null) { clazz = primitves.get(clazz); } try { method.invoke(value, clazz.getConstructor(String.class).newInstance(field)); } catch (NoSuchMethodException nsme) { // we are failed here, but so what? be lenient } } // we are done with string else if (clazz.isArray() || clazz.isAssignableFrom(List.class)) { // JSON array corresponds either to array type, or to some collection if (field instanceof JSONObject) { JSONArray array = new JSONArray(); array.put(field); field = array; } // we are interested in arrays for now if (clazz.isArray()) { // populate field value from JSON Array Object fieldValue = populateRecursive(clazz, field); method.invoke(value, fieldValue); } else if (clazz.isAssignableFrom(List.class)) { try { Type type = method.getGenericParameterTypes()[0]; if (type instanceof ParameterizedType) { Type param = ((ParameterizedType) type).getActualTypeArguments()[0]; if (param instanceof Class) { Class c = (Class) param; // populate field value from JSON Array Object fieldValue = populateRecursiveList(clazz, c, field); method.invoke(value, fieldValue); } } } catch (Exception e) { // failed } } } else if (field instanceof JSONObject) { // JSON object means nested bean - process recursively method.invoke(value, unmarshall((JSONObject) field, clazz)); } else if (clazz.equals(Date.class)) { method.invoke(value, new Date((Long) field)); } else { // fallback here, types not yet processed will be // set directly ( if possible ) // TODO: guard this? for better leniency method.invoke(value, field); } } } return value; }
From source file:org.protorabbit.json.DefaultSerializer.java
@SuppressWarnings("unchecked") void invokeMethod(Method[] methods, String key, String name, JSONObject jo, Object targetObject) { Object param = null;// w w w .j a va2 s . com Throwable ex = null; for (int i = 0; i < methods.length; i++) { Method m = methods[i]; if (m.getName().equals(name)) { Class<?>[] paramTypes = m.getParameterTypes(); if (paramTypes.length == 1 && jo.has(key)) { Class<?> tparam = paramTypes[0]; boolean allowNull = false; try { if (jo.isNull(key)) { // do nothing because param is already null : lets us not null on other types } else if (Long.class.isAssignableFrom(tparam) || tparam == long.class) { param = new Long(jo.getLong(key)); } else if (Double.class.isAssignableFrom(tparam) || tparam == double.class) { param = new Double(jo.getDouble(key)); } else if (Integer.class.isAssignableFrom(tparam) || tparam == int.class) { param = new Integer(jo.getInt(key)); } else if (String.class.isAssignableFrom(tparam)) { param = jo.getString(key); } else if (Enum.class.isAssignableFrom(tparam)) { param = Enum.valueOf((Class<? extends Enum>) tparam, jo.getString(key)); } else if (Boolean.class.isAssignableFrom(tparam)) { param = new Boolean(jo.getBoolean(key)); } else if (jo.isNull(key)) { param = null; allowNull = true; } else if (Collection.class.isAssignableFrom(tparam)) { if (m.getGenericParameterTypes().length > 0) { Type t = m.getGenericParameterTypes()[0]; if (t instanceof ParameterizedType) { ParameterizedType tv = (ParameterizedType) t; if (tv.getActualTypeArguments().length > 0 && tv.getActualTypeArguments()[0] == String.class) { List<String> ls = new ArrayList<String>(); JSONArray ja = jo.optJSONArray(key); if (ja != null) { for (int j = 0; j < ja.length(); j++) { ls.add(ja.getString(j)); } } param = ls; } else if (tv.getActualTypeArguments().length == 1) { ParameterizedType type = (ParameterizedType) tv.getActualTypeArguments()[0]; Class itemClass = (Class) type.getRawType(); if (itemClass == Map.class && type.getActualTypeArguments().length == 2 && type.getActualTypeArguments()[0] == String.class && type.getActualTypeArguments()[1] == Object.class) { List<Map<String, Object>> ls = new ArrayList<Map<String, Object>>(); JSONArray ja = jo.optJSONArray(key); if (ja != null) { for (int j = 0; j < ja.length(); j++) { Map<String, Object> map = new HashMap<String, Object>(); JSONObject mo = ja.getJSONObject(j); Iterator<String> keys = mo.keys(); while (keys.hasNext()) { String okey = keys.next(); Object ovalue = null; // make sure we don't get JSONObject$Null if (!mo.isNull(okey)) { ovalue = mo.get(okey); } map.put(okey, ovalue); } ls.add(map); } } param = ls; } else { getLogger().warning( "Don't know how to handle Collection of type : " + itemClass); } } else { getLogger().warning("Don't know how to handle Collection of type : " + tv.getActualTypeArguments()[0]); } } } } else { getLogger().warning( "Unable to serialize " + key + " : Don't know how to handle " + tparam); } } catch (JSONException e) { e.printStackTrace(); } if (param != null || allowNull) { try { if (m != null) { Object[] args = { param }; m.invoke(targetObject, args); ex = null; break; } } catch (SecurityException e) { ex = e; } catch (IllegalArgumentException e) { ex = e; } catch (IllegalAccessException e) { ex = e; } catch (InvocationTargetException e) { ex = e; } } } } } if (ex != null) { if (ex instanceof RuntimeException) { throw (RuntimeException) ex; } else { throw new RuntimeException(ex); } } }
From source file:com.vmware.photon.controller.swagger.resources.SwaggerJsonListing.java
/** * Gets all of the operation data for a method, such as http method, documentation, parameters, response class, etc. * * @param models The hashmap of models that are being documented so that they can be referenced by swagger-ui. * @param method The method to document. * @param parentParams The parameters of parent resources, so that they can be documented by subresources. * @return A SwaggerOperation API representation. *//*from ww w .java 2 s.com*/ private SwaggerOperation getOperation(HashMap<String, SwaggerModel> models, ResourceMethod method, List<SwaggerParameter> parentParams) { Method definitionMethod = method.getInvocable().getDefinitionMethod(); SwaggerOperation operation = new SwaggerOperation(); // If there is no @ApiOperation on a method we still document it because it's possible that the return class of // this method is a resource class with @Api and @ApiOperation on methods. ApiOperation apiOperation = definitionMethod.getAnnotation(ApiOperation.class); if (apiOperation != null) { operation.setSummary(apiOperation.value()); operation.setNotes(apiOperation.notes()); Class<?> responseClass = apiOperation.response().equals(Void.class) ? definitionMethod.getReturnType() : apiOperation.response(); if (StringUtils.isNotBlank(apiOperation.responseContainer())) { operation.setResponseClass(addListModel(models, responseClass, apiOperation.responseContainer())); } else { operation.setResponseClass( getTypeName(models, responseClass, definitionMethod.getGenericReturnType())); } addModel(models, responseClass); } operation.setHttpMethod(parseHttpOperation(definitionMethod)); operation.setNickname(definitionMethod.getName()); // In this block we get all of the parameters to the method and convert them to SwaggerParameter types. We // introspect the generic types. List<SwaggerParameter> swaggerParameters = new ArrayList<>(); Class[] parameterTypes = definitionMethod.getParameterTypes(); Type[] genericParameterTypes = definitionMethod.getGenericParameterTypes(); Annotation[][] parameterAnnotations = definitionMethod.getParameterAnnotations(); for (int i = 0; i < parameterTypes.length; i++) { Class parameter = parameterTypes[i]; Type genericParameterType = genericParameterTypes[i]; if (genericParameterType instanceof Class && "javax.ws.rs.core.Request".equals(((Class) genericParameterType).getName())) { continue; } SwaggerParameter swaggerParameter = parameterToSwaggerParameter(models, parameter, genericParameterType, parameterAnnotations[i]); swaggerParameters.add(swaggerParameter); // Add this parameter to the list of model documentation. addModel(models, parameter); } swaggerParameters.addAll(parentParams); operation.setParameters(swaggerParameters); return operation; }