Example usage for java.lang.reflect Constructor getParameterAnnotations

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

Introduction

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

Prototype

@Override
public Annotation[][] getParameterAnnotations() 

Source Link

Usage

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

/** Same as {@link #makeArgsFor(Method)}, but for a {@link Constructor} */
public Object[] makeArgsFor(Constructor cons) {
    return makeArgsFor(cons.getParameterTypes(), cons.getParameterAnnotations());
}

From source file:com.mewmew.fairy.v1.cli.AnnotatedCLI.java

public AnnotatedCLI(Class... clazz) {
    final List<AnnotatedOption> list = new ArrayList<AnnotatedOption>();
    for (Class aClass : clazz) {
        for (Field field : aClass.getDeclaredFields()) {
            Param param = field.getAnnotation(Param.class);
            if (param != null) {
                list.add(new AnnotatedOption(aClass, field, param));
            }//from  w w w .j  a v  a 2  s  . c om
            Args arg = field.getAnnotation(Args.class);
            if (arg != null) {
                args.put(aClass, field);
            }
        }
        for (Constructor ctor : aClass.getConstructors()) {
            AnnotatedConstructor actor = new AnnotatedConstructor(aClass, ctor);
            Class[] types = ctor.getParameterTypes();
            Annotation[][] annotations = ctor.getParameterAnnotations();
            for (int i = 0; i < types.length; i++) {
                Class type = types[i];
                Annotation[] ann = annotations[i];
                for (Annotation annotation : ann) {
                    if (annotation instanceof Param) {
                        actor.addParam((Param) annotation, type);
                    }
                }
            }
            if (actor.isValid()) {
                ctors.put(aClass, actor);
            }
        }
    }
    options = new Options();
    mappings = Multimaps.newMultimap(Maps.<Class, Collection<AnnotatedOption>>newHashMap(),
            new Supplier<Collection<AnnotatedOption>>() {
                public Collection<AnnotatedOption> get() {
                    return new ArrayList<AnnotatedOption>();
                }
            });
    for (AnnotatedConstructor constructor : ctors.values()) {
        for (AnnotatedConstructor.AnnotatedParam param : constructor.getParams()) {
            boolean hasArgs = !(param.getType().equals(boolean.class) || param.getType().equals(Boolean.class));
            String option = param.getParam().option();
            while (options.hasOption(option)) {
                option = option + option;
            }
            options.addOption(option, param.getParam().name(), hasArgs, param.getParam().desc());
        }
    }
    for (AnnotatedOption opt : list) {
        boolean hasArgs = !(opt.field.getType().equals(boolean.class)
                || opt.field.getType().equals(Boolean.class));
        while (options.hasOption(opt.getOpt())) {
            opt.setOpt(opt.getOpt() + opt.getOpt());
        }
        options.addOption(opt.getOpt(), opt.getName(), hasArgs, opt.getParam().desc());
        mappings.put(opt.clazz, opt);
    }
}

From source file:eu.tripledframework.eventstore.infrastructure.ReflectionObjectConstructor.java

private T createInstance(DomainEvent event) {
    Constructor constructor = getEventHandlerConstructor(event);
    if (constructor == null) {
        throw new AggregateRootReconstructionException(
                String.format("Could not find a suitable constructor for event %s", event));
    }//from   ww w  . ja v a 2s .co  m
    try {
        constructor.setAccessible(true);
        Object[] parameters = getParametersValues(constructor.getParameterAnnotations(), event);
        return (T) constructor.newInstance(parameters);
    } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
        throw new AggregateRootReconstructionException(
                String.format("Could not create object using constructor %s", constructor), e);
    }
}

From source file:com.agimatec.validation.jsr303.extensions.MethodValidatorMetaBeanFactory.java

private void buildConstructorConstraints(MethodBeanDescriptorImpl beanDesc)
        throws InvocationTargetException, IllegalAccessException {
    beanDesc.setConstructorConstraints(new HashMap());

    for (Constructor cons : beanDesc.getMetaBean().getBeanClass().getDeclaredConstructors()) {
        if (!factoryContext.getFactory().getAnnotationIgnores().isIgnoreAnnotations(cons)) {

            ConstructorDescriptorImpl consDesc = new ConstructorDescriptorImpl(beanDesc.getMetaBean(),
                    new Validation[0]);
            beanDesc.putConstructorDescriptor(cons, consDesc);

            Annotation[][] paramsAnnos = cons.getParameterAnnotations();
            Class[] paramTypes = cons.getParameterTypes();
            int idx = 0;
            for (Annotation[] paramAnnos : paramsAnnos) {
                processAnnotations(consDesc, paramAnnos, paramTypes[idx], idx);
                idx++;/* www . j a v  a 2 s. c  om*/
            }
        }
    }
}

From source file:com.thinkbiganalytics.policy.BasePolicyAnnotationTransformer.java

private P createClass(BaseUiPolicyRule rule) throws ClassNotFoundException, InvocationTargetException,
        NoSuchMethodException, InstantiationException, IllegalAccessException {
    P domainPolicy = null;//from   ww w .j a v  a  2 s . c om
    String classType = rule.getObjectClassType();
    Class<P> domainPolicyClass = (Class<P>) Class.forName(classType);

    Constructor constructor = null;
    Object[] paramValues = null;
    boolean hasConstructor = false;
    for (Constructor con : domainPolicyClass.getConstructors()) {
        hasConstructor = true;
        int parameterSize = con.getParameterTypes().length;
        paramValues = new Object[parameterSize];
        for (int p = 0; p < parameterSize; p++) {
            Annotation[] annotations = con.getParameterAnnotations()[p];
            Object paramValue = null;
            for (Annotation a : annotations) {
                if (a instanceof PolicyPropertyRef) {
                    // this is the one we want
                    if (constructor == null) {
                        constructor = con;
                    }
                    //find the value associated to this property
                    paramValue = getPropertyValue(rule, domainPolicyClass, (PolicyPropertyRef) a);

                }
            }
            paramValues[p] = paramValue;
        }
        if (constructor != null) {
            //exit once we find a constructor with @PropertyRef
            break;
        }

    }

    if (constructor != null) {
        //call that constructor
        try {
            domainPolicy = ConstructorUtils.invokeConstructor(domainPolicyClass, paramValues);
        } catch (NoSuchMethodException e) {
            domainPolicy = domainPolicyClass.newInstance();
        }
    } else {
        //if the class has no public constructor then attempt to call the static instance method
        if (!hasConstructor) {
            //if the class has a static "instance" method on it then call that
            try {
                domainPolicy = (P) MethodUtils.invokeStaticMethod(domainPolicyClass, "instance", null);
            } catch (NoSuchMethodException | SecurityException | InvocationTargetException e) {
                domainPolicy = domainPolicyClass.newInstance();
            }
        } else {
            //attempt to create a new instance
            domainPolicy = domainPolicyClass.newInstance();
        }

    }

    return domainPolicy;

}

From source file:com.github.hateoas.forms.spring.xhtml.XhtmlResourceMessageConverter.java

Object recursivelyCreateObject(Class<?> clazz, MultiValueMap<String, String> formValues,
        String parentParamName) {

    if (Map.class.isAssignableFrom(clazz)) {
        throw new IllegalArgumentException("Map not supported");
    } else if (Collection.class.isAssignableFrom(clazz)) {
        throw new IllegalArgumentException("Collection not supported");
    } else {/*  w w  w .  j  a v  a 2 s .c  o m*/
        try {
            Constructor[] constructors = clazz.getConstructors();
            Constructor constructor = PropertyUtils.findDefaultCtor(constructors);
            if (constructor == null) {
                constructor = PropertyUtils.findJsonCreator(constructors, JsonCreator.class);
            }
            Assert.notNull(constructor, "no default constructor or JsonCreator found");
            int parameterCount = constructor.getParameterTypes().length;
            Object[] args = new Object[parameterCount];
            if (parameterCount > 0) {
                Annotation[][] annotationsOnParameters = constructor.getParameterAnnotations();
                Class[] parameters = constructor.getParameterTypes();
                int paramIndex = 0;
                for (Annotation[] annotationsOnParameter : annotationsOnParameters) {
                    for (Annotation annotation : annotationsOnParameter) {
                        if (JsonProperty.class == annotation.annotationType()) {
                            JsonProperty jsonProperty = (JsonProperty) annotation;
                            String paramName = jsonProperty.value();
                            List<String> formValue = formValues.get(parentParamName + paramName);
                            Class<?> parameterType = parameters[paramIndex];
                            if (DataType.isSingleValueType(parameterType)) {
                                if (formValue != null) {
                                    if (formValue.size() == 1) {
                                        args[paramIndex++] = DataType.asType(parameterType, formValue.get(0));
                                    } else {
                                        //                                        // TODO create proper collection type
                                        throw new IllegalArgumentException("variable list not supported");
                                        //                                        List<Object> listValue = new ArrayList<Object>();
                                        //                                        for (String item : formValue) {
                                        //                                            listValue.add(DataType.asType(parameterType, formValue.get(0)));
                                        //                                        }
                                        //                                        args[paramIndex++] = listValue;
                                    }
                                } else {
                                    args[paramIndex++] = null;
                                }
                            } else {
                                args[paramIndex++] = recursivelyCreateObject(parameterType, formValues,
                                        parentParamName + paramName + ".");
                            }
                        }
                    }
                }
                Assert.isTrue(args.length == paramIndex,
                        "not all constructor arguments of @JsonCreator are " + "annotated with @JsonProperty");
            }
            Object ret = constructor.newInstance(args);
            BeanInfo beanInfo = Introspector.getBeanInfo(clazz);
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
            for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
                Method writeMethod = propertyDescriptor.getWriteMethod();
                String name = propertyDescriptor.getName();
                List<String> strings = formValues.get(name);
                if (writeMethod != null && strings != null && strings.size() == 1) {
                    writeMethod.invoke(ret,
                            DataType.asType(propertyDescriptor.getPropertyType(), strings.get(0))); // TODO lists, consume values from ctor
                }
            }
            return ret;
        } catch (Exception e) {
            throw new RuntimeException("Failed to instantiate bean " + clazz.getName(), e);
        }
    }
}

From source file:de.escalon.hypermedia.spring.hydra.LinkListSerializer.java

/**
 * Writes bean description recursively./*from   w  w w  . jav a 2 s . c o  m*/
 *
 * @param jgen
 *         to write to
 * @param currentVocab
 *         in context
 * @param valueType
 *         class of value
 * @param allRootParameters
 *         of the method that receives the request body
 * @param rootParameter
 *         the request body
 * @param currentCallValue
 *         the value at the current recursion level
 * @param propertyPath
 *         of the current recursion level
 * @throws IntrospectionException
 * @throws IOException
 */
private void recurseSupportedProperties(JsonGenerator jgen, String currentVocab, Class<?> valueType,
        ActionDescriptor allRootParameters, ActionInputParameter rootParameter, Object currentCallValue,
        String propertyPath) throws IntrospectionException, IOException {

    Map<String, ActionInputParameter> properties = new HashMap<String, ActionInputParameter>();

    // collect supported properties from ctor

    Constructor[] constructors = valueType.getConstructors();
    // find default ctor
    Constructor constructor = PropertyUtils.findDefaultCtor(constructors);
    // find ctor with JsonCreator ann
    if (constructor == null) {
        constructor = PropertyUtils.findJsonCreator(constructors, JsonCreator.class);
    }
    if (constructor == null) {
        // TODO this can be a generic collection, find a way to describe it
        LOG.warn("can't describe supported properties, no default constructor or JsonCreator found for type "
                + valueType.getName());
        return;
    }

    int parameterCount = constructor.getParameterTypes().length;
    if (parameterCount > 0) {
        Annotation[][] annotationsOnParameters = constructor.getParameterAnnotations();

        Class[] parameters = constructor.getParameterTypes();
        int paramIndex = 0;
        for (Annotation[] annotationsOnParameter : annotationsOnParameters) {
            for (Annotation annotation : annotationsOnParameter) {
                if (JsonProperty.class == annotation.annotationType()) {
                    JsonProperty jsonProperty = (JsonProperty) annotation;
                    // TODO use required attribute of JsonProperty
                    String paramName = jsonProperty.value();

                    Object propertyValue = PropertyUtils.getPropertyOrFieldValue(currentCallValue, paramName);

                    ActionInputParameter constructorParamInputParameter = new SpringActionInputParameter(
                            new MethodParameter(constructor, paramIndex), propertyValue);

                    // TODO collect ctor params, setter params and process
                    // TODO then handle single, collection and bean for both
                    properties.put(paramName, constructorParamInputParameter);
                    paramIndex++; // increase for each @JsonProperty
                }
            }
        }
        Assert.isTrue(parameters.length == paramIndex, "not all constructor arguments of @JsonCreator "
                + constructor.getName() + " are annotated with @JsonProperty");
    }

    // collect supported properties from setters

    // TODO support Option provider by other method args?
    final BeanInfo beanInfo = Introspector.getBeanInfo(valueType);
    final PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
    // TODO collection and map
    // TODO distinguish which properties should be printed as supported - now just setters
    for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
        final Method writeMethod = propertyDescriptor.getWriteMethod();
        if (writeMethod == null) {
            continue;
        }
        // TODO: the property name must be a valid URI - need to check context for terms?
        String propertyName = getWritableExposedPropertyOrPropertyName(propertyDescriptor);

        Object propertyValue = PropertyUtils.getPropertyOrFieldValue(currentCallValue,
                propertyDescriptor.getName());

        MethodParameter methodParameter = new MethodParameter(propertyDescriptor.getWriteMethod(), 0);
        ActionInputParameter propertySetterInputParameter = new SpringActionInputParameter(methodParameter,
                propertyValue);

        properties.put(propertyName, propertySetterInputParameter);
    }

    // write all supported properties
    // TODO we are using the annotatedParameter.parameterName but should use the key of properties here:
    for (ActionInputParameter annotatedParameter : properties.values()) {
        String nextPropertyPathLevel = propertyPath.isEmpty() ? annotatedParameter.getParameterName()
                : propertyPath + '.' + annotatedParameter.getParameterName();
        if (DataType.isSingleValueType(annotatedParameter.getParameterType())) {

            final Object[] possiblePropertyValues = rootParameter.getPossibleValues(allRootParameters);

            if (rootParameter.isIncluded(nextPropertyPathLevel)
                    && !rootParameter.isExcluded(nextPropertyPathLevel)) {
                writeSupportedProperty(jgen, currentVocab, annotatedParameter,
                        annotatedParameter.getParameterName(), possiblePropertyValues);
            }
            // TODO collections?
            //                        } else if (DataType.isArrayOrCollection(parameterType)) {
            //                            Object[] callValues = rootParameter.getValues();
            //                            int items = callValues.length;
            //                            for (int i = 0; i < items; i++) {
            //                                Object value;
            //                                if (i < callValues.length) {
            //                                    value = callValues[i];
            //                                } else {
            //                                    value = null;
            //                                }
            //                                recurseSupportedProperties(jgen, currentVocab, rootParameter
            // .getParameterType(),
            //                                        allRootParameters, rootParameter, value);
            //                            }
        } else {
            jgen.writeStartObject();
            jgen.writeStringField("hydra:property", annotatedParameter.getParameterName());
            // TODO: is the property required -> for bean props we need the Access annotation to express that
            jgen.writeObjectFieldStart(getPropertyOrClassNameInVocab(currentVocab, "rangeIncludes",
                    LdContextFactory.HTTP_SCHEMA_ORG, "schema:"));
            Expose expose = AnnotationUtils.getAnnotation(annotatedParameter.getParameterType(), Expose.class);
            String subClass;
            if (expose != null) {
                subClass = expose.value();
            } else {
                subClass = annotatedParameter.getParameterType().getSimpleName();
            }
            jgen.writeStringField(getPropertyOrClassNameInVocab(currentVocab, "subClassOf",
                    "http://www.w3" + ".org/2000/01/rdf-schema#", "rdfs:"), subClass);

            jgen.writeArrayFieldStart("hydra:supportedProperty");

            Object propertyValue = PropertyUtils.getPropertyOrFieldValue(currentCallValue,
                    annotatedParameter.getParameterName());

            recurseSupportedProperties(jgen, currentVocab, annotatedParameter.getParameterType(),
                    allRootParameters, rootParameter, propertyValue, nextPropertyPathLevel);
            jgen.writeEndArray();

            jgen.writeEndObject();
            jgen.writeEndObject();
        }
    }
}

From source file:dinistiq.Dinistiq.java

/**
 * Creates an instance of the given type and registeres it with the container.
 *
 * @param dependencies dependencies within the scope
 * @param cls type to create an instance of
 * @param beanName beans name in the scope using the given dependencies
 *//*from w ww.  j a  va2s .c om*/
private <T extends Object> T createInstance(Map<String, Set<Object>> dependencies, Class<T> cls,
        String beanName) throws Exception {
    LOG.info("createInstance({})", cls.getSimpleName());
    Constructor<?> c = null;
    Constructor<?>[] constructors = cls.getDeclaredConstructors();
    LOG.debug("createInstance({}) constructors.length={}", cls.getSimpleName(), constructors.length);
    for (Constructor<?> ctor : constructors) {
        LOG.debug("createInstance({}) {}", cls.getSimpleName(), ctor);
        c = (ctor.getAnnotation(Inject.class) != null) ? ctor : c;
    } // for
    c = (c == null) ? cls.getConstructor() : c;
    // Don't record constructor dependencies - they MUST be already fulfilled
    Object[] parameters = getParameters(null, null, beanName, c.getParameterTypes(),
            c.getGenericParameterTypes(), c.getParameterAnnotations());
    dependencies.put(beanName, new HashSet<>());
    boolean accessible = c.isAccessible();
    try {
        c.setAccessible(true);
        return convert(c.newInstance(parameters));
    } finally {
        c.setAccessible(accessible);
    } // try/finally
}

From source file:io.milton.config.HttpManagerBuilder.java

private Object createObject(Class c) throws CreationException {
    log.info("createObject: {}", c.getCanonicalName());
    // Look for an @Inject or default constructor
    Constructor found = null;//from  ww  w . j  a v a2  s. co m

    for (Constructor con : c.getConstructors()) {
        Annotation[][] paramTypes = con.getParameterAnnotations();
        if (paramTypes != null && paramTypes.length > 0) {
            Annotation inject = con.getAnnotation(Inject.class);
            if (inject != null) {
                found = con;
            }
        } else {
            found = con;
        }
    }
    if (found == null) {
        throw new RuntimeException(
                "Could not find a default or @Inject constructor for class: " + c.getCanonicalName());
    }
    Object args[] = new Object[found.getParameterTypes().length];
    int i = 0;
    for (Class paramType : found.getParameterTypes()) {
        try {
            args[i++] = findOrCreateObject(paramType);
        } catch (CreationException ex) {
            throw new CreationException(c, ex);
        }
    }
    Object created;
    try {
        log.info("Creating: {}", c.getCanonicalName());
        created = found.newInstance(args);
        rootContext.put(created);
    } catch (InstantiationException ex) {
        throw new CreationException(c, ex);
    } catch (IllegalAccessException ex) {
        throw new CreationException(c, ex);
    } catch (IllegalArgumentException ex) {
        throw new CreationException(c, ex);
    } catch (InvocationTargetException ex) {
        throw new CreationException(c, ex);
    }
    // Now look for @Inject fields
    for (Field field : c.getDeclaredFields()) {
        Inject anno = field.getAnnotation(Inject.class);
        if (anno != null) {
            boolean acc = field.isAccessible();
            try {
                field.setAccessible(true);
                field.set(created, findOrCreateObject(field.getType()));
            } catch (IllegalArgumentException ex) {
                throw new CreationException(field, c, ex);
            } catch (IllegalAccessException ex) {
                throw new CreationException(field, c, ex);
            } finally {
                field.setAccessible(acc); // put back the way it was
            }
        }
    }

    // Finally set any @Inject methods
    for (Method m : c.getMethods()) {
        Inject anno = m.getAnnotation(Inject.class);
        if (anno != null) {
            Object[] methodArgs = new Object[m.getParameterTypes().length];
            int ii = 0;
            try {
                for (Class<?> paramType : m.getParameterTypes()) {
                    methodArgs[ii++] = findOrCreateObject(paramType);
                }
                m.invoke(created, methodArgs);
            } catch (CreationException creationException) {
                throw new CreationException(m, c, creationException);
            } catch (IllegalAccessException ex) {
                throw new CreationException(m, c, ex);
            } catch (IllegalArgumentException ex) {
                throw new CreationException(m, c, ex);
            } catch (InvocationTargetException ex) {
                throw new CreationException(m, c, ex);
            }
        }
    }
    if (created instanceof InitListener) {
        if (listeners == null) {
            listeners = new ArrayList<InitListener>();
        }
        InitListener l = (InitListener) created;
        l.beforeInit(this); // better late then never!!
        listeners.add(l);
    }
    return created;
}