Example usage for java.lang.reflect Constructor getAnnotation

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

Introduction

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

Prototype

public <T extends Annotation> T getAnnotation(Class<T> annotationClass) 

Source Link

Usage

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

private Constructor getEventHandlerConstructor(DomainEvent event) {
    Set<Constructor> constructors = Arrays.stream(targetClass.getConstructors())
            .filter(contructor -> contructor.isAnnotationPresent(ConstructionHandler.class))
            .collect(Collectors.toSet());
    for (Constructor constructor : constructors) {
        ConstructionHandler constructionHandlerAnnotation = (ConstructionHandler) constructor
                .getAnnotation(ConstructionHandler.class);
        if (constructionHandlerAnnotation.value().equals(event.getClass())) {
            return constructor;
        }/*from   w ww. ja v  a  2  s .  co m*/
    }
    return null;
}

From source file:org.diorite.impl.bean.BeanScanner.java

private void processClass(final Class<?> clazz) throws BeanException {
    // Bean registration by class
    if (clazz.isAnnotationPresent(DioriteBean.class)) {
        final DioriteBean beanInfo = clazz.getAnnotation(DioriteBean.class);
        final BeanContainer beanContainer = new BeanContainer(clazz, new ClassBeanProvider(clazz));

        this.beanManager.registerBean(beanContainer);
    }/*from  ww w  .j  a  v  a2 s.c  om*/

    // Bean registration by constructor
    for (final Constructor<?> constructor : clazz.getConstructors()) {
        if (constructor.isAnnotationPresent(DioriteBean.class)) {
            final DioriteBean beanInfo = constructor.getAnnotation(DioriteBean.class);
            final BeanContainer beanContainer = new BeanContainer(clazz,
                    new ConstructorBeanProvider(constructor));

            this.beanManager.registerBean(beanContainer);
        }
    }

    // Bean registration by method
    for (final Method method : clazz.getMethods()) {
        if (method.isAnnotationPresent(DioriteBean.class)) {
            final Class<?> returnType = method.getReturnType();
            if (returnType.equals(Void.TYPE) || returnType.isPrimitive()) {
                throw new BeanRegisteringException(MessageFormat.format(
                        "Can't register method '{0}' in class '{1}' as Diorite Bean. Method must return object.",
                        method.getName(), clazz.getName()));
            } else if (returnType.getPackage().equals(JAVA_PACKAGE)) {
                throw new BeanRegisteringException(MessageFormat.format(
                        "Can't register method '{0}' in class '{1}' as Diorite Bean. Method can't return object from java package.",
                        method.getName(), clazz.getName()));
            }
            final DioriteBean beanInfo = method.getAnnotation(DioriteBean.class);

            final BeanContainer beanContainer = new BeanContainer(returnType, new MethodBeanProvider(method));
            this.beanManager.registerBean(beanContainer);
        }
    }

    for (final Field field : clazz.getDeclaredFields()) {
        if (field.isAnnotationPresent(InjectedValue.class)) {
            this.beanManager.addInjectorCode(clazz);
            break;
        }
    }
}

From source file:eu.sathra.io.IO.java

private SerializeInfo getSerializeInfo(Class<?> clazz) {
    if (!mCache.containsKey(clazz)) {
        SerializeInfo myInfo = new SerializeInfo();

        // Find annotated constructor
        for (Constructor<?> myConstructor : clazz.getConstructors()) {
            Deserialize myDeserialize = myConstructor.getAnnotation(Deserialize.class);

            myInfo.types = myConstructor.getParameterTypes();

            if (myDeserialize != null) {
                myInfo.constructor = myConstructor;
                Defaults myDefaults = myConstructor.getAnnotation(Defaults.class);

                myInfo.params = myDeserialize.value();

                if (myDefaults != null)
                    myInfo.defaults = myDefaults.value();

                mCache.put(clazz, myInfo);
                break;
            }/*from   w w w .  jav a 2s .  c  om*/

        }
    }

    return mCache.get(clazz);
}

From source file:gobblin.runtime.cli.ConstructorAndPublicMethodsCliObjectFactory.java

private boolean canUseConstructor(Constructor<?> constructor) {
    if (!Modifier.isPublic(constructor.getModifiers())) {
        return false;
    }//from   w w w .j  a  v  a2  s.co  m
    if (!constructor.isAnnotationPresent(CliObjectSupport.class)) {
        return false;
    }
    for (Class<?> param : constructor.getParameterTypes()) {
        if (param != String.class) {
            return false;
        }
    }
    return constructor.getParameterTypes().length == constructor.getAnnotation(CliObjectSupport.class)
            .argumentNames().length;
}

From source file:gobblin.runtime.cli.ConstructorAndPublicMethodsGobblinCliFactory.java

private boolean canUseConstructor(Constructor<?> constructor) {
    if (!Modifier.isPublic(constructor.getModifiers())) {
        return false;
    }//from   www  .  j  a  v  a  2 s  . c o m
    if (!constructor.isAnnotationPresent(EmbeddedGobblinCliSupport.class)) {
        return false;
    }
    for (Class<?> param : constructor.getParameterTypes()) {
        if (param != String.class) {
            return false;
        }
    }
    return constructor.getParameterTypes().length == constructor.getAnnotation(EmbeddedGobblinCliSupport.class)
            .argumentNames().length;
}

From source file:gobblin.runtime.cli.ConstructorAndPublicMethodsCliObjectFactory.java

private Constructor<? extends T> inferConstructorOptions(Options otherOptions) {
    Constructor<? extends T> selectedConstructor = null;
    for (Constructor<?> constructor : this.klazz.getConstructors()) {
        if (canUseConstructor(constructor)) {
            if (selectedConstructor == null) {
                selectedConstructor = (Constructor<? extends T>) constructor;
            } else {
                throw new RuntimeException("Multiple usable constructors for " + this.klazz.getName());
            }//from  w w  w  . j  a v a 2  s.c  o  m
        }
    }
    if (selectedConstructor == null) {
        throw new RuntimeException("There is no usable constructor for " + this.klazz.getName());
    }

    int constructorIdx = 0;
    for (String argument : selectedConstructor.getAnnotation(CliObjectSupport.class).argumentNames()) {
        Option option = Option.builder(argument).required().hasArg().build();
        otherOptions.addOption(option);
        constructoArgumentsMap.put(option.getOpt(), constructorIdx);
        constructorIdx++;
    }

    return selectedConstructor;
}

From source file:gobblin.runtime.cli.ConstructorAndPublicMethodsGobblinCliFactory.java

private Constructor<? extends EmbeddedGobblin> inferConstructorOptions(Options otherOptions) {
    Constructor<? extends EmbeddedGobblin> selectedConstructor = null;
    for (Constructor<?> constructor : this.klazz.getConstructors()) {
        if (canUseConstructor(constructor)) {
            if (selectedConstructor == null) {
                selectedConstructor = (Constructor<? extends EmbeddedGobblin>) constructor;
            } else {
                throw new RuntimeException("Multiple usable constructors for " + this.klazz.getName());
            }/*ww w.  j  av a  2 s  . co  m*/
        }
    }
    if (selectedConstructor == null) {
        throw new RuntimeException("There is no usable constructor for " + this.klazz.getName());
    }

    int constructorIdx = 0;
    for (String argument : selectedConstructor.getAnnotation(EmbeddedGobblinCliSupport.class).argumentNames()) {
        Option option = Option.builder(argument).required().hasArg().build();
        otherOptions.addOption(option);
        constructoArgumentsMap.put(option.getOpt(), constructorIdx);
        constructorIdx++;
    }

    return selectedConstructor;
}

From source file:org.springframework.web.method.annotation.ModelAttributeMethodProcessor.java

/**
 * Construct a new attribute instance with the given constructor.
 * <p>Called from/*from w  w w . j  av a  2  s.co  m*/
 * {@link #createAttribute(String, MethodParameter, WebDataBinderFactory, NativeWebRequest)}
 * after constructor resolution.
 * @param ctor the constructor to use
 * @param attributeName the name of the attribute (never {@code null})
 * @param binderFactory for creating WebDataBinder instance
 * @param webRequest the current request
 * @return the created model attribute (never {@code null})
 * @throws BindException in case of constructor argument binding failure
 * @throws Exception in case of constructor invocation failure
 * @since 5.0
 */
protected Object constructAttribute(Constructor<?> ctor, String attributeName,
        WebDataBinderFactory binderFactory, NativeWebRequest webRequest) throws Exception {

    if (ctor.getParameterCount() == 0) {
        // A single default constructor -> clearly a standard JavaBeans arrangement.
        return BeanUtils.instantiateClass(ctor);
    }

    // A single data class constructor -> resolve constructor arguments from request parameters.
    ConstructorProperties cp = ctor.getAnnotation(ConstructorProperties.class);
    String[] paramNames = (cp != null ? cp.value() : parameterNameDiscoverer.getParameterNames(ctor));
    Assert.state(paramNames != null, () -> "Cannot resolve parameter names for constructor " + ctor);
    Class<?>[] paramTypes = ctor.getParameterTypes();
    Assert.state(paramNames.length == paramTypes.length,
            () -> "Invalid number of parameter names: " + paramNames.length + " for constructor " + ctor);

    Object[] args = new Object[paramTypes.length];
    WebDataBinder binder = binderFactory.createBinder(webRequest, null, attributeName);
    String fieldDefaultPrefix = binder.getFieldDefaultPrefix();
    String fieldMarkerPrefix = binder.getFieldMarkerPrefix();
    boolean bindingFailure = false;

    for (int i = 0; i < paramNames.length; i++) {
        String paramName = paramNames[i];
        Class<?> paramType = paramTypes[i];
        Object value = webRequest.getParameterValues(paramName);
        if (value == null) {
            if (fieldDefaultPrefix != null) {
                value = webRequest.getParameter(fieldDefaultPrefix + paramName);
            }
            if (value == null && fieldMarkerPrefix != null) {
                if (webRequest.getParameter(fieldMarkerPrefix + paramName) != null) {
                    value = binder.getEmptyValue(paramType);
                }
            }
        }
        try {
            MethodParameter methodParam = new MethodParameter(ctor, i);
            if (value == null && methodParam.isOptional()) {
                args[i] = (methodParam.getParameterType() == Optional.class ? Optional.empty() : null);
            } else {
                args[i] = binder.convertIfNecessary(value, paramType, methodParam);
            }
        } catch (TypeMismatchException ex) {
            ex.initPropertyName(paramName);
            binder.getBindingErrorProcessor().processPropertyAccessException(ex, binder.getBindingResult());
            bindingFailure = true;
            args[i] = value;
        }
    }

    if (bindingFailure) {
        if (binder.getBindingResult() instanceof AbstractBindingResult) {
            AbstractBindingResult result = (AbstractBindingResult) binder.getBindingResult();
            for (int i = 0; i < paramNames.length; i++) {
                result.recordFieldValue(paramNames[i], paramTypes[i], args[i]);
            }
        }
        throw new BindException(binder.getBindingResult());
    }

    return BeanUtils.instantiateClass(ctor, args);
}

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
 */// www .j  a v a 2 s.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:org.evosuite.setup.TestClusterGenerator.java

public static boolean canUse(Constructor<?> c) {

    if (c.isSynthetic()) {
        return false;
    }//w ww.j  a va  2s .co  m

    // synthetic constructors are OK
    if (Modifier.isAbstract(c.getDeclaringClass().getModifiers()))
        return false;

    // TODO we could enable some methods from Object, like getClass
    //if (c.getDeclaringClass().equals(java.lang.Object.class))
    //   return false;// handled here to avoid printing reasons

    if (c.getDeclaringClass().equals(java.lang.Thread.class))
        return false;// handled here to avoid printing reasons

    if (c.getDeclaringClass().isAnonymousClass())
        return false;

    if (c.getDeclaringClass().isLocalClass()) {
        logger.debug("Skipping constructor of local class {}", c.getName());
        return false;
    }

    if (c.getDeclaringClass().isMemberClass() && !canUse(c.getDeclaringClass()))
        return false;

    if (!Properties.USE_DEPRECATED && c.getAnnotation(Deprecated.class) != null) {
        logger.debug("Skipping deprecated constructor {}", c.getName());
        return false;
    }

    if (isForbiddenNonDeterministicCall(c)) {
        return false;
    }

    if (Modifier.isPublic(c.getModifiers())) {
        makeAccessible(c);
        return true;
    }

    // If default access rights, then check if this class is in the same package as the target class
    if (!Modifier.isPrivate(c.getModifiers())) {
        //              && !Modifier.isProtected(c.getModifiers())) {
        String packageName = ClassUtils.getPackageName(c.getDeclaringClass());
        if (packageName.equals(Properties.CLASS_PREFIX)) {
            makeAccessible(c);
            return true;
        }
    }

    return false;
}