Java Code Examples for java.lang.reflect.Parameter#getParameterizedType()

The following examples show how to use java.lang.reflect.Parameter#getParameterizedType() . 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 Schema createSchemaFromParameter(Parameter parameter, String parameterName) {
	Schema schema;
	Class<?> clazz = parameter.getType();
	Annotation[] annotations = parameter.getAnnotations();

	if (clazz.isPrimitive()) {
		schema = schemaGeneratorHelper.parseBaseTypeSignature(clazz, annotations);
	} else if (clazz.isArray()) {
		schema = schemaGeneratorHelper.parseArraySignature(clazz.getComponentType(), null, annotations);
	} else if (clazz.isAssignableFrom(List.class)) {
		if (parameter.getParameterizedType() instanceof ParameterizedType) {
			Class<?> listGenericParameter = (Class<?>)((ParameterizedType) parameter.getParameterizedType()).getActualTypeArguments()[0];
			return schemaGeneratorHelper.parseArraySignature(listGenericParameter, null, annotations);
		}

		throw new IllegalArgumentException(String.format("List [%s] not being parametrized type.", parameterName));
	} else {
		schema = schemaGeneratorHelper.parseClassRefTypeSignature(clazz, annotations, null);
	}
	return schema;
}
 
Example 2
Source File: LaActionExecuteUtil.java    From lastaflute with Apache License 2.0 6 votes vote down vote up
protected static Map<Integer, Class<?>> prepareOptionalGenericTypeMap(Method executeMethod) {
    final Parameter[] parameters = executeMethod.getParameters();
    if (parameters.length == 0) {
        return Collections.emptyMap();
    }
    final Map<Integer, Class<?>> optionalGenericTypeMap = new LinkedHashMap<Integer, Class<?>>(4);
    int index = 0;
    for (Parameter parameter : parameters) {
        if (isOptionalParameterType(parameter.getType())) {
            final Type paramedType = parameter.getParameterizedType();
            final Class<?> genericType = DfReflectionUtil.getGenericFirstClass(paramedType);
            optionalGenericTypeMap.put(index, genericType);
        }
        ++index;
    }
    return Collections.unmodifiableMap(optionalGenericTypeMap);
}
 
Example 3
Source File: ExecuteArgAnalyzer.java    From lastaflute with Apache License 2.0 6 votes vote down vote up
protected void checkNonGenericParameter(Method executeMethod, Parameter parameter) {
    if (isNonGenericCheckTargetType(parameter.getType())) { // e.g. List
        final Type paramedType = parameter.getParameterizedType();
        if (paramedType == null) { // no way? no check just in case
            return;
        }
        if (paramedType instanceof ParameterizedType) {
            final Type[] typeArgs = ((ParameterizedType) paramedType).getActualTypeArguments();
            if (typeArgs != null && typeArgs.length > 0 && "?".equals(typeArgs[0].getTypeName())) { // e.g. List<?>
                throwActionFormWildcardOnlyListParameterException(executeMethod, parameter);
            }
        } else {
            throwActionFormNonGenericListParameterException(executeMethod, parameter);
        }
    }
}
 
Example 4
Source File: ExecuteArgAnalyzer.java    From lastaflute with Apache License 2.0 6 votes vote down vote up
protected Map<Integer, Class<?>> prepareOptionalGenericTypeMap(Method executeMethod) {
    final Parameter[] parameters = executeMethod.getParameters();
    if (parameters.length == 0) {
        return Collections.emptyMap();
    }
    final Map<Integer, Class<?>> optionalGenericTypeMap = new LinkedHashMap<Integer, Class<?>>(4);
    int index = 0;
    for (Parameter parameter : parameters) {
        if (isOptionalParameterType(parameter.getType())) {
            final Type paramedType = parameter.getParameterizedType();
            final Class<?> genericType = DfReflectionUtil.getGenericFirstClass(paramedType);
            checkExecuteMethodOptionalParameter(executeMethod, paramedType, genericType);
            optionalGenericTypeMap.put(index, genericType);
        }
        ++index;
    }
    return Collections.unmodifiableMap(optionalGenericTypeMap);
}
 
Example 5
Source File: SerDesMiddleware.java    From enkan with Eclipse Public License 1.0 6 votes vote down vote up
private void deserializeBody(Method method, HttpRequest request) throws IOException {
    String contentType = HttpRequestUtils.contentType(request);
    if (contentType == null) return;

    String[] mediaTypeTokens = contentType.split("/", 2);
    if (mediaTypeTokens.length == 2) {
        MediaType mediaType = new MediaType(mediaTypeTokens[0], mediaTypeTokens[1]);
        Parameter[] parameters = method != null ? method.getParameters() : new Parameter[0];
        BodyDeserializable bodyDeserializable = BodyDeserializable.class.cast(request);
        for (Parameter parameter : parameters) {
            Class<?> type = parameter.getType();
            Type genericType = parameter.getParameterizedType();

            if (parameterInjectors.stream().anyMatch(injector-> injector.isApplicable(type, request)))
                continue;

            Object body = deserialize(request, type, genericType, mediaType);
            bodyDeserializable.setDeserializedBody(body);
        }
        if (bodyDeserializable.getDeserializedBody() == null) {
            bodyDeserializable.setDeserializedBody(deserialize(request, Object.class, Object.class, mediaType));
        }
    }
}
 
Example 6
Source File: ProxyGenerator.java    From vlingo-actors with Mozilla Public License 2.0 6 votes vote down vote up
private String parameterTypesFor(final Method method) {
  final StringBuilder builder = new StringBuilder();

  String separator = ", ";
  int parameterIndex = 0;
  final Parameter[] parameters = method.getParameters();

  for (final Parameter parameter : parameters) {
    final Type type = parameter.getParameterizedType();
    builder.append(type.getTypeName().replace('$', '.'));
    if (++parameterIndex < parameters.length) {
      builder.append(separator);
    }
  }

  return builder.toString();
}
 
Example 7
Source File: MethodParameter.java    From pippo with Apache License 2.0 6 votes vote down vote up
public Class<?> getParameterGenericType() {
    if (parameterGenericType == null) {
        Parameter parameter = getParameter();

        Type parameterType = parameter.getParameterizedType();
        if (!ParameterizedType.class.isAssignableFrom(parameterType.getClass())) {
            throw new PippoRuntimeException("Please specify a generic parameter type for '{}' of '{}'",
                getParameterName(), LangUtils.toString(method));
        }

        ParameterizedType parameterizedType = (ParameterizedType) parameterType;
        try {
            parameterGenericType = (Class<?>) parameterizedType.getActualTypeArguments()[0];
        } catch (ClassCastException e) {
            throw new PippoRuntimeException("Please specify a generic parameter type for '{}' of '{}'",
                getParameterName(), LangUtils.toString(method));
        }
    }

    return parameterGenericType;
}
 
Example 8
Source File: OperationsTransformer.java    From spring-openapi with MIT License 6 votes vote down vote up
private void fillParameterInfo(AbstractSerializableParameter<?> oasParameter, Parameter parameter, String parameterName) {
	Class<?> clazz = parameter.getType();
	Annotation[] annotations = parameter.getAnnotations();

	if (clazz.isPrimitive()) {
		setParameterDetails(oasParameter, clazz, annotations);
	} else if (clazz.isArray()) {
		oasParameter.setProperty(parseArraySignatureForParameter(clazz.getComponentType(), annotations));
	} else if (clazz.isAssignableFrom(List.class)) {
		if (!(parameter.getParameterizedType() instanceof ParameterizedType)) {
			throw new IllegalArgumentException(String.format("List [%s] not being parametrized type.", parameterName));
		}
		Class<?> listGenericParameter = (Class<?>) ((ParameterizedType) parameter.getParameterizedType()).getActualTypeArguments()[0];
		oasParameter.setProperty(parseArraySignature(listGenericParameter, null, annotations));
	} else {
		setParameterDetails(oasParameter, clazz, annotations);
	}
}
 
Example 9
Source File: ParameterModel.java    From DevToolBox with GNU Lesser General Public License v2.1 5 votes vote down vote up
public ParameterizedType getParameterizedType() {
    for (Parameter p : method.getParameters()) {
        if (p.getName().equals(name) || String.format("arg%d", index).equals(p.getName())) {
            if (p.getParameterizedType() instanceof ParameterizedType) {
                return (ParameterizedType) p.getParameterizedType();
            }
        }
    }
    return null;
}
 
Example 10
Source File: JavassistGrpcFactory.java    From joyrpc with Apache License 2.0 5 votes vote down vote up
@Override
protected Class<?> buildRequestClass(final Class<?> clz, final Method method, final Naming naming) throws Exception {
    //ClassPool:CtClass对象的容器
    ClassPool pool = ClassPool.getDefault();
    //通过ClassPool生成一个public新类
    CtClass ctClass = pool.makeClass(naming.getFullName());
    ctClass.setInterfaces(new CtClass[]{pool.getCtClass(Serializable.class.getName()), pool.getCtClass(MethodArgs.class.getName())});
    //添加字段
    CtField ctField;
    String name;
    String typeName;
    Type type;
    int i = 0;
    StringBuilder toArgs = new StringBuilder(100).append("public Object[] toArgs(){\n\treturn new Object[]{");
    StringBuilder toFields = new StringBuilder(200).append("public void toFields(Object[] args){\n");
    for (Parameter parameter : method.getParameters()) {
        name = parameter.getName();
        type = parameter.getParameterizedType();
        typeName = type.getTypeName();
        ctField = new CtField(pool.getCtClass(typeName), name, ctClass);
        ctField.setModifiers(Modifier.PRIVATE);
        ctClass.addField(ctField);
        if (i > 0) {
            toArgs.append(',');
        }
        toArgs.append(name);
        toFields.append('\t').append(name).append("=(").append(typeName).append(")args[").append(i).append("];\n");
        name = name.substring(0, 1).toUpperCase() + name.substring(1);
        ctClass.addMethod(CtNewMethod.getter((boolean.class == type ? "is" : "get") + name, ctField));
        ctClass.addMethod(CtNewMethod.setter("set" + name, ctField));
        i++;
    }
    toArgs.append("};\n};");
    toFields.append("};");
    ctClass.addMethod(CtMethod.make(toArgs.toString(), ctClass));
    ctClass.addMethod(CtMethod.make(toFields.toString(), ctClass));
    return ctClass.toClass();
}
 
Example 11
Source File: AbstractMethodParameterParser.java    From RestDoc with Apache License 2.0 5 votes vote down vote up
@Override
public ParameterModel parse(Parameter parameter, ParamJavadoc paramJavadoc, ParameterModel parameterModel) {
    parameterModel.setName(getParameterName(parameter));

    if (paramJavadoc != null)
    {
        parameterModel.setDescription(FormatUtils.format(paramJavadoc.getComment()));
    }
    // 参数是Optional类型
    Type actualParamType = parameter.getParameterizedType();
    if (parameter.getType() == Optional.class)
    {
        if (parameter.getParameterizedType() instanceof ParameterizedType)
        {
            actualParamType = ((ParameterizedType)parameter.getParameterizedType()).getActualTypeArguments()[0];
        }
        else
        {
            throw new RuntimeException("why?");
        }
    }
    parameterModel.setParameterType(actualParamType);

    parameterModel.setLocation(getParameterLocation(parameter, actualParamType));
    parameterModel = parseInternal(parameter, actualParamType, parameterModel);
    parameterModel.setRequired(isRequired(parameter, actualParamType));

    if (actualParamType != parameter.getParameterizedType())
        parameterModel.setRequired(false);

    return parameterModel;
}
 
Example 12
Source File: InjectionPoint.java    From baratine with GNU General Public License v2.0 5 votes vote down vote up
static <T> InjectionPoint<T> of(Parameter p)
{
  return new InjectionPointImpl<>((Key<T>) Key.of(p),
      p.getParameterizedType(),
      p.getName(),
      p.getAnnotations(),
      p.getDeclaringExecutable().getDeclaringClass());
}
 
Example 13
Source File: ExecuteArgAnalyzer.java    From lastaflute with Apache License 2.0 5 votes vote down vote up
protected Class<?> findListFormGenericType(Parameter parameter) {
    if (isListTypeParameter(parameter)) {
        final Type pt = parameter.getParameterizedType();
        final Class<?> genericType = DfReflectionUtil.getGenericFirstClass(pt); // almost not null, already checked
        return genericType != null && isBeanActionFormType(genericType) ? genericType : null; // e.g. List<SeaForm>
    }
    return null;
}
 
Example 14
Source File: OperationsTransformer.java    From spring-openapi with MIT License 5 votes vote down vote up
private Class<?> getGenericParam(Parameter parameter) {
	if (parameter.getParameterizedType() instanceof ParameterizedType) {
		ParameterizedType parameterizedType = (ParameterizedType) parameter.getParameterizedType();
		if (isNotEmpty(parameterizedType.getActualTypeArguments())) {
			return (Class<?>) parameterizedType.getActualTypeArguments()[0];
		}
	}
	return null;
}
 
Example 15
Source File: OperationsTransformer.java    From spring-openapi with MIT License 5 votes vote down vote up
private Class<?> getGenericParam(Parameter parameter) {
	if (parameter.getParameterizedType() instanceof ParameterizedType) {
		ParameterizedType parameterizedType = (ParameterizedType) parameter.getParameterizedType();
		if (isNotEmpty(parameterizedType.getActualTypeArguments())) {
			return (Class<?>) parameterizedType.getActualTypeArguments()[0];
		}
	}
	return null;
}
 
Example 16
Source File: BaseConfigurator.java    From configuration-as-code-plugin with MIT License 4 votes vote down vote up
public static TypePair of(Parameter parameter) {
return new TypePair(parameter.getParameterizedType(), parameter.getType());        }
 
Example 17
Source File: ParamUtils.java    From servicecomb-java-chassis with Apache License 2.0 4 votes vote down vote up
public static Type getGenericParameterType(Class<?> mainClass, Method method, Parameter param) {
  Type type = param.getParameterizedType();
  return getGenericParameterType(mainClass, method.getDeclaringClass(), type);
}
 
Example 18
Source File: ParameterModelService.java    From component-runtime with Apache License 2.0 4 votes vote down vote up
public Param(final Parameter parameter) {
    this(parameter.getParameterizedType(), parameter.getAnnotations(), parameter.getName());
}
 
Example 19
Source File: GenerateIfaceCommand.java    From baratine with GNU General Public License v2.0 4 votes vote down vote up
private static void methodToString(StringBuilder sb,
                                   Method method,
                                   boolean isUseReturnType)
{
  if (isUseReturnType) {
    TypeVariable []typeVars = method.getTypeParameters();

    if (typeVars.length > 0) {
      sb.append("<");

      for (int i = 0; i < typeVars.length; i++) {
        if (i != 0) {
          sb.append(",");
        }

        sb.append(typeVars[i]);
      }

      sb.append(">");
      sb.append(" ");
    }

    sb.append("void " + method.getName() + "(");
  }

  Parameter []parameters = method.getParameters();
  for (int i = 0; i < parameters.length; i++ ) {
    if (i > 0) {
      sb.append(", ");
    }

    Parameter param = parameters[i];

    if (isUseReturnType && param.getParameterizedType() != null) {
      typeToString(sb, param.getParameterizedType(), false);
    }
    else {
      typeToString(sb, param.getType(), false);
    }

    sb.append(" " + param.getName());
  }

  if (isUseReturnType) {
    Type returnType = method.getGenericReturnType();

    if (returnType != void.class) {
      if (parameters.length > 0) {
        sb.append(", ");
      }

      sb.append("Result<");
      typeToString(sb, returnType, true);
      sb.append("> __result");
    }
  }

  sb.append(")");
}
 
Example 20
Source File: Key.java    From baratine with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Builds Key from parameter's parameterized type and and qualifying annotations
 * found on the parameter and its declaring executable (e.g. Method)
 *
 * @param parameter parameter for deriving type and annotations from
 * @return instance of a key
 */
public static Key<?> of(Parameter parameter)
{
  return new Key(parameter.getParameterizedType(),
                 qualifiers(parameter.getAnnotations(),
                            parameter.getDeclaringExecutable().getAnnotations()));
}