Example usage for java.lang.reflect Method getParameterAnnotations

List of usage examples for java.lang.reflect Method getParameterAnnotations

Introduction

In this page you can find the example usage for java.lang.reflect Method getParameterAnnotations.

Prototype

@Override
public Annotation[][] getParameterAnnotations() 

Source Link

Usage

From source file:com.ankang.report.pool.AbstractReportAliasPool.java

private void mountPrams(LinkedHashMap<String, Class<?>> paramsType, Method method) {

    Class<?>[] parameterTypes = method.getParameterTypes();

    Annotation[][] annotations = method.getParameterAnnotations();

    for (int i = 0; i < parameterTypes.length; i++) {

        if (annotations.length < i) {
            throw new ReportException(
                    "Please add an effective note for the argument, such as: HTTPParam, RequestParam");
        }/*from  ww  w . ja v  a 2s .  co m*/
        if ((ReportRequest.class.isAssignableFrom(parameterTypes[i]))
                || (!parameterTypes[i].isPrimitive() && !parameterTypes[i].toString().matches("^.+java\\..+$")
                        && parameterTypes[i].toString().matches("^class.+$"))) {

            Field[] fields = parameterTypes[i].getDeclaredFields();
            for (Field field : fields) {
                if (!Modifier.isFinal(field.getModifiers()) || !Modifier.isStatic(field.getModifiers())) {

                    paramsType.put(field.getName(), field.getType());
                }
            }
        } else {
            if (annotations.length >= i && annotations[i].length > 0) {

                paramsType.put(matchPrams(annotations[i][0]), parameterTypes[i]);
            }
        }
    }
}

From source file:org.sybila.parasim.core.impl.ExtensionImpl.java

public ExtensionImpl(Class<? extends Annotation> scope, Class<?> targetClass) throws Exception {
    Validate.notNull(scope);/*from  w  ww.ja  v a2  s .  c om*/
    Validate.notNull(targetClass);
    this.scope = ReflectionUtils.clean(scope);
    this.targetClass = targetClass;
    Object target = ReflectionUtils.createInstance(targetClass);
    // find injection points
    List<InjectionPoint> newInjectionPoints = new ArrayList<>();
    for (Field field : targetClass.getDeclaredFields()) {
        if (field.getAnnotation(Inject.class) != null) {
            newInjectionPoints.add(new InjectionField(field, targetClass));
        }
    }
    injectionPoints = Collections.unmodifiableCollection(newInjectionPoints);
    // find observing methods
    List<ObservingPoint> newObservingPoints = new ArrayList<>();
    for (Method method : targetClass.getDeclaredMethods()) {
        if (method.getParameterTypes().length > 0 && ReflectionUtils
                .loadAnnotation(method.getParameterAnnotations()[0], Observes.class) != null) {
            newObservingPoints.add(new ObservingMethod(target, method));
        }
    }
    observingPoints = Collections.unmodifiableCollection(newObservingPoints);
    // find providing points
    // -- fields
    List<ProvidingPoint> newProvidingPoints = new ArrayList<>();
    for (Field field : targetClass.getDeclaredFields()) {
        if (field.getAnnotation(Provide.class) != null) {
            newProvidingPoints.add(new ProvidingField(field, target));
        }
    }
    // -- methods
    for (Method method : targetClass.getDeclaredMethods()) {
        if (method.getAnnotation(Provide.class) != null) {
            newProvidingPoints.add(new ProvidingMethod(method, target));
        }
    }
    providingPoints = Collections.unmodifiableCollection(newProvidingPoints);
}

From source file:com.laxser.blitz.web.paramresolver.ParameterNameDiscovererImpl.java

public String[] getParameterNames(Method method) {
    Class<?>[] parameterTypes = method.getParameterTypes();
    Annotation[][] parameterAnnotations = method.getParameterAnnotations();
    String[] names = new String[parameterTypes.length];
    Map<String, Integer> counts = new HashMap<String, Integer>();
    for (int i = 0; i < names.length; i++) {
        Annotation[] annotations = parameterAnnotations[i];
        for (Annotation annotation : annotations) {
            String name = null;/*from ww  w.j a  va 2  s  .c om*/
            if (annotation instanceof Param) {
                name = ((Param) annotation).value();
            } else if (annotation instanceof FlashParam) {
                name = ((FlashParam) annotation).value();
            }
            if (name != null) {
                if (StringUtils.isNotEmpty(name)) {
                    names[i] = name;
                    if ((parameterTypes[i] == BindingResult.class || parameterTypes[i] == Errors.class)
                            && !name.endsWith("BindingResult")) {
                        names[i] = name + "BindingResult";
                    }
                }
                break;
            }
        }
        if (names[i] != null) {
            continue;
        }
        if (parameterTypes[i] == BindingResult.class || parameterTypes[i] == Errors.class) {
            if (i > 0 && names[i - 1] != null) {
                names[i] = names[i - 1] + "BindingResult";
                continue;
            }
        }
        String rawName = getParameterRawName(parameterTypes[i]);
        if (rawName == null) {
            continue;
        }
        names[i] = rawName;
        Integer count = counts.get(rawName);
        if (count == null) {
            counts.put(rawName, 1);
        } else {
            counts.put(rawName, count + 1);
            if (count == 1) {
                for (int j = 0; j < i; j++) {
                    if (names[j] != null && names[j].equals(rawName)) {
                        names[j] = rawName + "1";
                        break;
                    }
                }
            }
            if (names[i] == rawName) {
                names[i] = names[i] + (count + 1);
            }
        }
    }
    Set<String> uniques = new HashSet<String>();
    for (String name : names) {
        if (name == null) {
            continue;
        }
        if (uniques.contains(name)) {
            // action????@Param?
            throw new IllegalArgumentException("params with same name: '" + name + "'");
        }
        uniques.add(name);
    }
    return names;
}

From source file:com.nominanuda.hyperapi.HyperApiWsSkelton.java

protected Object[] createArgs(DataObject uriParams, HttpEntity entity, Class<?> api2, Method method)
        throws IOException {
    Annotation[][] parameterAnnotations = method.getParameterAnnotations();
    Class<?>[] parameterTypes = method.getParameterTypes();
    Object[] args = new Object[parameterTypes.length];
    for (int i = 0; i < parameterTypes.length; i++) {
        Class<?> parameterType = parameterTypes[i];
        Annotation[] annotations = parameterAnnotations[i];
        AnnotatedType p = new AnnotatedType(parameterType, annotations);
        boolean annotationFound = false;
        for (Annotation annotation : annotations) {
            if (annotation instanceof PathParam) {
                annotationFound = true;/*ww  w .  jav  a2s  .  c  om*/
                String s = (String) uriParams.getPathSafe(((PathParam) annotation).value());
                args[i] = cast(s, parameterType);
                break;
            } else if (annotation instanceof QueryParam) {
                annotationFound = true;
                String s = (String) uriParams.getPathSafe(((QueryParam) annotation).value());
                args[i] = cast(s, parameterType);
                break;
            }
        }
        if (!annotationFound) {
            Object dataEntity = entity == null ? null : decodeEntity(entity, p);
            args[i] = dataEntity;
        }
    }
    return args;
}

From source file:org.callimachusproject.rewrite.ProxyPostAdvice.java

private synchronized Integer getBodyIndex(Method method) {
    if (bodyFluidType == null)
        return null;
    Integer ret = bodyIndices.get(method);
    if (ret != null)
        return ret;
    Annotation[][] panns = method.getParameterAnnotations();
    for (int i = panns.length - 1; i >= 0; i--) {
        for (Annotation ann : panns[i]) {
            if (ann instanceof Iri) {
                if (((Iri) ann).value().equals(bodyIri)) {
                    bodyIndices.put(method, i);
                    return i;
                }/*  w ww.  ja va 2  s . c o m*/
            }
        }
    }
    return null;
}

From source file:org.frat.common.validation.ValidateInterceptor.java

/**
 * validate the business logic before executing target method.
 *//*from   w  w w.j av  a2 s .com*/
@Before("findValidateAnnotation()")
public void validate(final JoinPoint jp) throws ConstraintViolationException {
    final Signature signature = jp.getSignature();
    final Object[] args = jp.getArgs();
    final MethodSignature methodSignature = (MethodSignature) signature;
    final Method targetMethod = methodSignature.getMethod();
    Set<ConstraintViolation<?>> result = new HashSet<ConstraintViolation<?>>();
    final Annotation[][] paraAnnotations = targetMethod.getParameterAnnotations();
    // get the parameters annotations
    if (paraAnnotations != null && paraAnnotations.length > 0) {
        for (int i = 0; i < paraAnnotations.length; i++) {
            int paraAnnotationLength = paraAnnotations[i].length;
            // current parameter annotation length
            if (paraAnnotationLength == 0) {
                // no annotation on current parameter
                continue;
            }
            for (int j = 0; j < paraAnnotationLength; j++) {
                if (paraAnnotations[i][j] instanceof OnValid) {
                    OnValid validated = (OnValid) (paraAnnotations[i][j]);
                    Class<?>[] groups = validated.value();
                    Object validatedObj = args[i];
                    executeValidate(validatedObj, groups, result);
                    break;
                }
            }
        }
    }
    if (!result.isEmpty()) {
        throw new ConstraintViolationException(result);
    }
}

From source file:com.medallia.tiny.ObjectProvider.java

/**
 * Creates a parameter list for invoking the method using object from this ObjectProvider.
 * Parameters are obtained by calling {@link #get(Class)} on the classes in m.getParameterTypes().
 * If a lastArg is specified for this ObjectProvider, the last argument will be that object.
 *///from  w  ww .  ja  v a  2 s .c  om
public Object[] makeArgsFor(Method m) {
    Class<?>[] pt = m.getParameterTypes();
    Annotation[][] a = m.getParameterAnnotations();
    return makeArgsFor(pt, a);
}

From source file:com.axelor.shell.core.Target.java

public Target(Method method, Object instance) {
    this.method = method;
    this.instance = instance;
    for (Annotation[] annotations : method.getParameterAnnotations()) {
        for (Annotation annotation : annotations) {
            if (annotation instanceof CliOption) {
                cliOptions.add((CliOption) annotation);
            }/*from www.j  a  v a  2  s . co  m*/
        }
    }

    final Class<?>[] types = method.getParameterTypes();
    if (cliOptions.size() == types.length - 1 && (types[types.length - 1].isArray())) {
        cliOptions.add(null); // variable arguments
    }

    cliCommand = method.getAnnotation(CliCommand.class);
}

From source file:org.blocks4j.feature.toggle.parameters.ParametersToggleHandler.java

private void extractParameterToggleIndexes(Method method, Map<Integer, String> parameterToggleIndexes) {
    int index = 0;
    for (Annotation[] parameterAnnotations : method.getParameterAnnotations()) {
        for (Annotation annotation : parameterAnnotations) {
            if (annotation instanceof ParameterToggle) {
                parameterToggleIndexes.put(index, ((ParameterToggle) annotation).value());
            }/*from  w ww .  j  a  v  a  2s. c  o  m*/
        }
        index++;
    }
}

From source file:com.doitnext.http.router.DefaultInvoker.java

@Override
public InvokeResult invokeMethod(HttpMethod method, PathMatch pm, HttpServletRequest req,
        HttpServletResponse resp) throws ServletException {
    String terminus = pm.getMatchedPath().getTerminus();

    // Extract variables from the path
    Map<String, PathElement> variableMatches = new HashMap<String, PathElement>();
    for (int x = 0; x < pm.getMatchedPath().size(); x++) {
        PathElement p = pm.getMatchedPath().get(x);
        if (!p.getType().equalsIgnoreCase("LITERAL")) {
            variableMatches.put(p.getName(), p);
        }/*from  w  w w  . j  av a 2 s  .  c o  m*/
    }

    Route route = pm.getRoute();

    Method implMethod = route.getImplMethod();

    Annotation[][] parameterAnnotations = implMethod.getParameterAnnotations();
    Class<?>[] parameterTypes = implMethod.getParameterTypes();
    Object[] arguments = new Object[parameterTypes.length];
    try {
        // First map annotated parameters, and HttpServletRequest 
        // and HttpServletResponse parameters to arguments.
        mapParametersToArguments(parameterAnnotations, parameterTypes, variableMatches, req, resp, terminus, pm,
                arguments);
        if (logger.isDebugEnabled()) {
            logger.debug(String.format("Invoking %s", route));
        }
        Object invocationResult = implMethod.invoke(route.getImplInstance(), arguments);
        if (logger.isTraceEnabled()) {
            logger.trace(String.format("Returned %s from %s", objectMapper.writeValueAsString(invocationResult),
                    route));
        }
        if (route.getSuccessHandler().handleResponse(pm, req, resp, invocationResult))
            return InvokeResult.METHOD_SUCCESS;
        else
            return InvokeResult.METHOD_SUCCESS_UNHANDLED;
    } catch (InvocationTargetException ite) {
        if (logger.isDebugEnabled()) {
            logger.debug(String.format("Invocation threw a %s %s", ite.getCause().getClass().getSimpleName(),
                    ite.getCause().getMessage()));
        }
        if (route.getErrorHandler().handleResponse(pm, req, resp, ite.getCause()))
            return InvokeResult.METHOD_ERROR;
        else
            return InvokeResult.METHOD_ERROR_UNHANDLED;
    } catch (Exception e) {
        throw new ServletException(String.format("Error invoking %s", route), e);
    }
}