Example usage for java.lang.reflect Method isAnnotationPresent

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

Introduction

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

Prototype

@Override
public boolean isAnnotationPresent(Class<? extends Annotation> annotationClass) 

Source Link

Usage

From source file:com.googlecode.jsonschema2pojo.integration.EnumIT.java

@Test
public void enumContainsWorkingAnnotatedDeserializationMethod()
        throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {

    Method fromValue = enumClass.getMethod("fromValue", String.class);

    assertThat((Enum) fromValue.invoke(enumClass, "one"), is(sameInstance(enumClass.getEnumConstants()[0])));
    assertThat((Enum) fromValue.invoke(enumClass, "secondOne"),
            is(sameInstance(enumClass.getEnumConstants()[1])));
    assertThat((Enum) fromValue.invoke(enumClass, "3rd one"),
            is(sameInstance(enumClass.getEnumConstants()[2])));

    assertThat(fromValue.isAnnotationPresent(JsonCreator.class), is(true));

}

From source file:com.opensymphony.xwork2.util.finder.DefaultClassFinder.java

public List<Method> findAnnotatedMethods(Class<? extends Annotation> annotation) {
    classesNotLoaded.clear();//from w w w.ja v  a2 s . com
    List<ClassInfo> seen = new ArrayList<ClassInfo>();
    List<Method> methods = new ArrayList<Method>();
    List<Info> infos = getAnnotationInfos(annotation.getName());
    for (Info info : infos) {
        if (info instanceof MethodInfo && !"<init>".equals(info.getName())) {
            MethodInfo methodInfo = (MethodInfo) info;
            ClassInfo classInfo = methodInfo.getDeclaringClass();

            if (seen.contains(classInfo))
                continue;

            seen.add(classInfo);

            try {
                Class clazz = classInfo.get();
                for (Method method : clazz.getDeclaredMethods()) {
                    if (method.isAnnotationPresent(annotation)) {
                        methods.add(method);
                    }
                }
            } catch (Throwable e) {
                LOG.error("Error loading class [{}]", classInfo.getName(), e);
                classesNotLoaded.add(classInfo.getName());
            }
        }
    }
    return methods;
}

From source file:nl.knaw.dans.common.ldap.repo.LdapMapper.java

private void populateMethodLists() {
    annotatedGetMethods = Collections.synchronizedList(new ArrayList<Method>());
    annotatedSetMethods = Collections.synchronizedList(new ArrayList<Method>());
    Class<?> superC = clazz;
    while (superC != null) {
        Method[] methods = superC.getDeclaredMethods();
        for (Method method : methods) {
            if (method.isAnnotationPresent(LdapAttribute.class)) {
                if (method.getReturnType().equals(void.class)) {
                    // this is a setter method
                    annotatedSetMethods.add(method);
                } else {
                    // its a getter method
                    annotatedGetMethods.add(method);
                }//from   w w  w  .  j  a v a  2 s.c om
            }
        }
        superC = superC.getSuperclass();
    }
}

From source file:org.apache.struts2.convention.DefaultClassFinder.java

public List<Method> findAnnotatedMethods(Class<? extends Annotation> annotation) {
    classesNotLoaded.clear();/*w  ww .  ja v  a2s.c  om*/
    List<ClassInfo> seen = new ArrayList<>();
    List<Method> methods = new ArrayList<>();
    List<Info> infos = getAnnotationInfos(annotation.getName());
    for (Info info : infos) {
        if (info instanceof MethodInfo && !"<init>".equals(info.getName())) {
            MethodInfo methodInfo = (MethodInfo) info;
            ClassInfo classInfo = methodInfo.getDeclaringClass();

            if (seen.contains(classInfo))
                continue;

            seen.add(classInfo);

            try {
                Class clazz = classInfo.get();
                for (Method method : clazz.getDeclaredMethods()) {
                    if (method.isAnnotationPresent(annotation)) {
                        methods.add(method);
                    }
                }
            } catch (Throwable e) {
                LOG.error("Error loading class [{}]", classInfo.getName(), e);
                classesNotLoaded.add(classInfo.getName());
            }
        }
    }
    return methods;
}

From source file:com.haulmont.chile.core.loader.ChileAnnotationsLoader.java

protected boolean isMetaPropertyMethod(Method method) {
    return method.isAnnotationPresent(com.haulmont.chile.core.annotations.MetaProperty.class);
}

From source file:org.jsonschema2pojo.integration.EnumIT.java

@Test
public void enumContainsWorkingAnnotatedSerializationMethod() throws NoSuchMethodException {

    Method toString = enumClass.getMethod("value");

    assertThat(enumClass.getEnumConstants()[0].toString(), is("one"));
    assertThat(enumClass.getEnumConstants()[1].toString(), is("secondOne"));
    assertThat(enumClass.getEnumConstants()[2].toString(), is("3rd one"));

    assertThat(toString.isAnnotationPresent(JsonValue.class), is(true));

}

From source file:com.khs.sherpa.servlet.request.DefaultSherpaRequest.java

protected void hasPermission(Method method, String userid, String token) {
    SessionTokenService service = null;//w  w  w. j a v  a  2  s.  c  o m
    try {
        service = applicationContext.getManagedBean(SessionTokenService.class);
    } catch (NoSuchManagedBeanExcpetion e) {
        throw new SherpaRuntimeException(e);
    }

    if (method.isAnnotationPresent(DenyAll.class)) {
        throw new SherpaPermissionExcpetion("method [" + method.getName() + "] in class ["
                + method.getDeclaringClass().getCanonicalName() + "] has `@DenyAll` annotation", "DENY_ALL");
    }

    if (method.isAnnotationPresent(RolesAllowed.class)) {
        boolean fail = true;
        for (String role : method.getAnnotation(RolesAllowed.class).value()) {
            if (service.hasRole(userid, token, role)) {
                fail = false;
            }
        }
        if (fail) {
            throw new SherpaPermissionExcpetion("method [" + method.getName() + "] in class ["
                    + method.getDeclaringClass().getCanonicalName() + "] has `@RolesAllowed` annotation",
                    "DENY_ROLE");
        }
    }
}

From source file:org.traccar.database.QueryBuilder.java

public <T> Collection<T> executeQuery(Class<T> clazz) throws SQLException {
    List<T> result = new LinkedList<>();

    if (query != null) {

        try {//from   w  w w .j  ava  2s .  co  m

            try (ResultSet resultSet = statement.executeQuery()) {

                ResultSetMetaData resultMetaData = resultSet.getMetaData();

                List<ResultSetProcessor<T>> processors = new LinkedList<>();

                Method[] methods = clazz.getMethods();

                for (final Method method : methods) {
                    if (method.getName().startsWith("set") && method.getParameterTypes().length == 1
                            && !method.isAnnotationPresent(QueryIgnore.class)) {

                        final String name = method.getName().substring(3);

                        // Check if column exists
                        boolean column = false;
                        for (int i = 1; i <= resultMetaData.getColumnCount(); i++) {
                            if (name.equalsIgnoreCase(resultMetaData.getColumnLabel(i))) {
                                column = true;
                                break;
                            }
                        }
                        if (!column) {
                            continue;
                        }

                        addProcessors(processors, method.getParameterTypes()[0], method, name);
                    }
                }

                while (resultSet.next()) {
                    try {
                        T object = clazz.newInstance();
                        for (ResultSetProcessor<T> processor : processors) {
                            processor.process(object, resultSet);
                        }
                        result.add(object);
                    } catch (InstantiationException | IllegalAccessException e) {
                        throw new IllegalArgumentException();
                    }
                }
            }

        } finally {
            statement.close();
            connection.close();
        }
    }

    return result;
}

From source file:com.github.blazeds.replicator.HibernateAdapter.java

@Override
public Object invoke(Message message) {

    // Init filter cache on first visit
    if (filterCache == null) {
        filterCache = new HashMap<Method, ReplicationPropertyFilter>();
    }//  ww  w.  j  av a2 s  .c  om

    // Invoke incoming service call via blazeds
    Object result = super.invoke(message);
    if (result == null) {
        return null;
    }

    // Get method and check for filter in cache
    Method method = getMethod(message);
    ReplicationPropertyFilter filter;
    if (filterCache.containsKey(method)) {

        filter = filterCache.get(method);
        if (filter == null) {
            // If no filter defined for this method do nothing
            return result;
        } else {
            replicator = new Hibernate3BeanReplicator(null, null, filter);
        }
    } else {

        // Get the annotation
        if (!method.isAnnotationPresent(ReplicateResult.class)) {
            // Add null value to cache to denote that the result from this
            // method does not need replication
            filterCache.put(method, null);
            return result;
        } else {
            // Initialize a new filter for this method using the replication
            // configuration
            ReplicateResult replicationConfig = method.getAnnotation(ReplicateResult.class);
            filter = new ReplicationPropertyFilter(replicationConfig);
            filterCache.put(method, filter);
            replicator = new Hibernate3BeanReplicator(null, null, filter);
        }
    }

    // Nullify lazy collections if fetch eager set to false
    if (!filter.isFetchEager()) {
        NullifyLazyTransformer.Factory factory = new NullifyLazyTransformer.Factory();
        replicator.initCustomTransformerFactory(factory);
    }

    // Bean lib only handles beans not collections
    if (result instanceof Collection<?>) {
        CollectionWrapper wrapper = new CollectionWrapper();
        wrapper.setCollection((Collection<?>) result);
        result = replicator.copy(wrapper).getCollection();
    } else {
        result = replicator.copy(result);
    }

    return result;
}

From source file:net.zcarioca.zcommons.config.data.BeanPropertySetterFactory.java

/**
 * Gets a collection of {@link BeanPropertySetter} to configure the bean.
 *
 * @param bean The bean to configure.//from  w w w . j  av a  2s .c o  m
 * @return Returns a collection of {@link BeanPropertySetter}.
 * @throws ConfigurationException
 */
public Collection<BeanPropertySetter> getPropertySettersForBean(Object bean) throws ConfigurationException {
    List<BeanPropertySetter> setters = new ArrayList<BeanPropertySetter>();
    Map<String, PropertyDescriptor> descriptors = new HashMap<String, PropertyDescriptor>();

    Class<?> beanClass = bean.getClass();

    try {
        BeanInfo beanInfo = Introspector.getBeanInfo(beanClass);
        for (PropertyDescriptor desc : beanInfo.getPropertyDescriptors()) {
            Method reader = desc.getReadMethod();
            Method writer = desc.getWriteMethod();
            Field field = getField(beanClass, desc);

            if (reader != null) {
                descriptors.put(desc.getDisplayName(), desc);
            }

            if (writer != null) {
                if (writer.isAnnotationPresent(ConfigurableAttribute.class)) {
                    setters.add(new WriterBeanPropertySetter(bean, desc, field,
                            writer.getAnnotation(ConfigurableAttribute.class)));
                    descriptors.remove(desc.getDisplayName());
                }
                if (reader != null && reader.isAnnotationPresent(ConfigurableAttribute.class)) {
                    setters.add(new WriterBeanPropertySetter(bean, desc, field,
                            reader.getAnnotation(ConfigurableAttribute.class)));
                    descriptors.remove(desc.getDisplayName());
                }
            }
        }
    } catch (Throwable t) {
        throw new ConfigurationException("Could not introspect bean class", t);
    }
    do {
        Field[] fields = beanClass.getDeclaredFields();
        for (Field field : fields) {
            if (field.isAnnotationPresent(ConfigurableAttribute.class)) {
                if (descriptors.containsKey(field.getName())
                        && descriptors.get(field.getName()).getWriteMethod() != null) {
                    PropertyDescriptor desc = descriptors.get(field.getName());
                    setters.add(new WriterBeanPropertySetter(bean, desc, field,
                            field.getAnnotation(ConfigurableAttribute.class)));
                } else {
                    setters.add(new FieldBeanPropertySetter(bean, null, field,
                            field.getAnnotation(ConfigurableAttribute.class)));
                }
            } else if (descriptors.containsKey(field.getName())) {
                // the annotation may have been set on the getter, not the field
                PropertyDescriptor desc = descriptors.get(field.getName());
                if (desc.getReadMethod().isAnnotationPresent(ConfigurableAttribute.class)) {
                    setters.add(new FieldBeanPropertySetter(bean, desc, field,
                            desc.getReadMethod().getAnnotation(ConfigurableAttribute.class)));
                }
            }
        }
    } while ((beanClass = beanClass.getSuperclass()) != null);
    return setters;
}