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:edu.stanford.epad.common.plugins.impl.ClassFinderTestUtils.java

public static List<Method> findMethodsWithAnnotation(Class<?> testClass,
        Class<? extends Annotation> annotationClass) {
    List<Method> retVal = new ArrayList<Method>();
    for (Method method : testClass.getMethods()) {
        if (method.isAnnotationPresent(PluginHandler.class)) {
            retVal.add(method);//from   w ww .  ja va  2  s. c om
            logger.info("Found ePad plugin-class: " + testClass.getName());
        }
    }
    return retVal;
}

From source file:org.jspare.forvertx.web.collector.HandlerCollector.java

private static boolean hasHttpMethodsPresents(Method method) {

    return getHttpMethodsPresents(method).stream()
            .filter(annotation -> method.isAnnotationPresent(annotation.annotationType())).count() >= 1;
}

From source file:net.solarnetwork.util.ClassUtils.java

/**
 * Get a Map of non-null bean properties for an object.
 * //w  w w .jav a  2 s  .  c  om
 * @param o the object to inspect
 * @param ignore a set of property names to ignore (optional)
 * @param serializeIgnore if <em>true</em> test for the {@link SerializeIgnore}
 * annotation for ignoring properties
 * @return Map (never null)
 */
public static Map<String, Object> getBeanProperties(Object o, Set<String> ignore, boolean serializeIgnore) {
    if (o == null) {
        return null;
    }
    if (ignore == null) {
        ignore = DEFAULT_BEAN_PROP_NAME_IGNORE;
    }
    Map<String, Object> result = new LinkedHashMap<String, Object>();
    BeanWrapper bean = PropertyAccessorFactory.forBeanPropertyAccess(o);
    PropertyDescriptor[] props = bean.getPropertyDescriptors();
    for (PropertyDescriptor prop : props) {
        if (prop.getReadMethod() == null) {
            continue;
        }
        String propName = prop.getName();
        if (ignore != null && ignore.contains(propName)) {
            continue;
        }
        Object propValue = bean.getPropertyValue(propName);
        if (propValue == null) {
            continue;
        }
        if (serializeIgnore) {
            Method getter = prop.getReadMethod();
            if (getter != null && getter.isAnnotationPresent(SerializeIgnore.class)) {
                continue;
            }
        }
        result.put(propName, propValue);
    }
    return result;
}

From source file:org.jspare.forvertx.web.collector.HandlerCollector.java

private static boolean isHandler(Method method) {

    return getHandlersPresents(method).stream()
            .filter(handlerAnnotation -> method.isAnnotationPresent(handlerAnnotation.annotationType()))
            .count() >= 1;/*from  w  w  w.j a  v  a  2 s. c  om*/
}

From source file:reconf.client.elements.ConfigurationItemElement.java

public static List<ConfigurationItemElement> from(ConfigurationRepositoryElement repository) {
    List<ConfigurationItemElement> result = new ArrayList<ConfigurationItemElement>();
    for (Method method : repository.getInterfaceClass().getMethods()) {

        ConfigurationItem ann = method.getAnnotation(ConfigurationItem.class);
        if (ann == null) {
            if (method.isAnnotationPresent(UpdateConfigurationRepository.class)) {
                continue;
            }//from   w w w. j  ava2s . co  m
            throw new ReConfInitializationError(msg.format("error.not.configured.method", method.toString()));
        }

        ConfigurationItemElement resultItem = null;

        for (ConfigurationItemElement item : repository.getConfigurationItems()) {
            if (StringUtils.equals(item.getMethodName(), method.getName())) {
                resultItem = item;
            }
        }

        if (resultItem == null) {
            resultItem = new ConfigurationItemElement();
            resultItem.setMethod(method.getName());
            resultItem.setAdapter(ann.adapter());
            resultItem.setValue(ann.value());
            resultItem.setQualifier(ann.qualifier());
        }
        resultItem.setMethod(method);
        defineItemProductComponentOverride(repository, resultItem, ann);
        result.add(resultItem);
    }
    return result;
}

From source file:net.sourceforge.stripes.integration.spring.SpringHelper.java

/**
 * Fetches the methods on a class that are annotated with SpringBean. The first time it
 * is called for a particular class it will introspect the class and cache the results.
 * All non-overridden methods are examined, including protected and private methods.
 * If a method is not public an attempt it made to make it accessible - if it fails
 * it is removed from the collection and an error is logged.
 *
 * @param clazz the class on which to look for SpringBean annotated methods
 * @return the collection of methods with the annotation
 *//*from  w ww  . j  av  a  2 s. c om*/
protected static Collection<Method> getMethods(Class<?> clazz) {
    Collection<Method> methods = methodMap.get(clazz);
    if (methods == null) {
        methods = ReflectUtil.getMethods(clazz);
        Iterator<Method> iterator = methods.iterator();

        while (iterator.hasNext()) {
            Method method = iterator.next();
            if (!method.isAnnotationPresent(SpringBean.class)) {
                iterator.remove();
            } else {
                // If the method isn't public, try to make it accessible
                if (!method.isAccessible()) {
                    try {
                        method.setAccessible(true);
                    } catch (SecurityException se) {
                        throw new StripesRuntimeException("Method " + clazz.getName() + "." + method.getName()
                                + "is marked " + "with @SpringBean and is not public. An attempt to call "
                                + "setAccessible(true) resulted in a SecurityException. Please "
                                + "either make the method public or modify your JVM security "
                                + "policy to allow Stripes to setAccessible(true).", se);
                    }
                }

                // Ensure the method has only the one parameter
                if (method.getParameterTypes().length != 1) {
                    throw new StripesRuntimeException(
                            "A method marked with @SpringBean must have exactly one parameter: "
                                    + "the bean to be injected. Method [" + method.toGenericString() + "] has "
                                    + method.getParameterTypes().length + " parameters.");
                }
            }
        }

        methodMap.put(clazz, methods);
    }

    return methods;
}

From source file:bdi4jade.util.ReflectionUtils.java

private static void setupParameters(Object obj1, Direction[] dir1, Object obj2, Direction[] dir2)
        throws ParameterException {
    for (Method method : obj1.getClass().getMethods()) {
        if (method.isAnnotationPresent(Parameter.class)) {
            Parameter parameter = method.getAnnotation(Parameter.class);

            if (!isParameterIn(parameter, dir1)) {
                continue;
            }//from  w  ww. jav  a 2s.co  m

            if (!(isGetter(method) || isSetter(method))) {
                checkSkipIsOK(parameter, "Method " + method + " should be a getter or setter.", null);
                continue;
            }

            String property = null;
            Method setter = null;

            if (isGetter(method)) {
                property = methodToPropertyName(GETTER_PREFIX, method);
                try {
                    setter = obj1.getClass().getMethod(propertyToMethodName(SETTER_PREFIX, property),
                            method.getReturnType());
                } catch (NoSuchMethodException nsme) {
                    checkSkipIsOK(parameter, "There is no setter method associated with property " + property,
                            nsme);
                    continue;
                }
            } else {
                property = methodToPropertyName(SETTER_PREFIX, method);
                setter = method;
            }

            Method getter = null;
            try {
                getter = obj2.getClass().getMethod(propertyToMethodName(GETTER_PREFIX, property));
                if (!getter.isAnnotationPresent(Parameter.class)
                        || !isParameterIn(getter.getAnnotation(Parameter.class), dir2)) {
                    checkSkipIsOK(parameter,
                            "There is no parameter associated with method " + method + " name " + property,
                            null);
                    continue;
                }
            } catch (NoSuchMethodException nsme) {
                checkSkipIsOK(parameter, "There is no getter method associated with property " + property,
                        nsme);
                continue;
            }

            try {
                setter.invoke(obj1, getter.invoke(obj2));
            } catch (Exception exc) {
                checkSkipIsOK(parameter, "An unknown error occurrred.", exc);
            }
        }
    }
}

From source file:nz.co.senanque.validationengine.ValidationUtils.java

public static Map<String, Property> getProperties(Class<? extends ValidationObject> class1) {
    Map<String, Property> ret = new HashMap<>(class1.getMethods().length);
    for (Method method : class1.getMethods()) {
        final String fieldName = ValidationUtils.getFieldNameFromGetterMethodName(method.getName());
        if (!ValidationUtils.isUsefulField(fieldName, null)) {
            continue;
        }/*from  w w  w.j  a  v a 2s . c  om*/
        Method getter = ValidationUtils.figureGetter(fieldName, class1);
        if (getter.isAnnotationPresent(Ignore.class)) {
            continue;
        }
        Method setter = ValidationUtils.figureSetter(fieldName, class1);
        ret.put(fieldName, new Property(fieldName, getter, setter, class1));
    }
    return ret;

}

From source file:org.evosuite.setup.TestClusterUtils.java

/**
 * Determine if this class contains JUnit tests
 * @deprecated use {@code org.evosuite.junit.CoverageAnalysis.isTest(Class<?> cls)}
 *
 * @param className//from  www .  j  a v a2s .co m
 * @return
 */
@Deprecated
public static boolean isTest(String className) {
    // TODO-JRO Identifying tests should be done differently:
    // If the class either contains methods
    // annotated with @Test (> JUnit 4.0)
    // or contains Test or Suite in it's inheritance structure
    try {
        Class<?> clazz = TestGenerationContext.getInstance().getClassLoaderForSUT().loadClass(className);
        Class<?> superClazz = clazz.getSuperclass();
        while (!superClazz.equals(Object.class)) {
            if (superClazz.equals(Suite.class))
                return true;
            if (superClazz.equals(Test.class))
                return true;

            superClazz = clazz.getSuperclass();
        }
        for (Method method : clazz.getMethods()) {
            if (method.isAnnotationPresent(Test.class)) {
                return true;
            }
        }
    } catch (ClassNotFoundException e) {
        logger.info("Could not load class: ", className);
    }
    return false;
}

From source file:com.startechup.tools.ModelParser.java

/**
 * Gets the values from the {@link JSONObject JSONObjects}/response returned from an api call
 * request and assign it to the field inside the class that will contain the parsed values.
 *
 * @param classModel The class type that will contain the parse value.
 * @param jsonObject The API response object.
 * @return Returns a generic class containing the values from the json, null if exception occurs.
 *//*from w  w w . j av  a2s  .  co  m*/
public static <T> T parse(Class<T> classModel, JSONObject jsonObject) {
    Object object = getNewInstance(classModel);

    if (object != null) {
        // TODO this solution is much accurate but not flexible when using a 3rd party library
        // for object model creation like squidb from yahoo, annotation should be added to the class method
        // and we cannot do that on squidb generated Class model.
        for (Method method : classModel.getDeclaredMethods()) {
            if (method.isAnnotationPresent(SetterSpec.class)) {
                SetterSpec methodLinker = method.getAnnotation(SetterSpec.class);
                String jsonKey = methodLinker.jsonKey();

                initMethodInvocation(method, object, jsonKey, jsonObject);
            }
        }
        return classModel.cast(object);
    } else {
        return null;
    }
}