Example usage for java.lang.reflect Field isAnnotationPresent

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

Introduction

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

Prototype

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

Source Link

Usage

From source file:kina.utils.UtilMongoDB.java

/**
 * Utility method that filters out all the fields _not_ annotated
 * with the {@link kina.annotations.Field} annotation.
 *
 * @param clazz the Class object for which we want to resolve kina fields.
 * @return an array of kina Field(s).//from ww  w .  j  av a  2s.  co  m
 */
public static java.lang.reflect.Field[] filterKinaFields(Class clazz) {
    java.lang.reflect.Field[] fields = Utils.getAllFields(clazz);
    List<java.lang.reflect.Field> filtered = new ArrayList<>();
    for (java.lang.reflect.Field f : fields) {
        if (f.isAnnotationPresent(kina.annotations.Field.class) || f.isAnnotationPresent(Key.class)) {

            filtered.add(f);
        }
    }
    return filtered.toArray(new java.lang.reflect.Field[filtered.size()]);
}

From source file:org.bigmouth.nvwa.utils.url.URLDecoder.java

/**
 * URL???//from w w  w  .  j a va  2s  .c om
 * 
 * @param <T>
 * @param url
 * ?URL?
 * <ul>
 * <li>http://www.big-mouth.cn/nvwa-utils/xml/decoder?id=123&json_data=bbb</li>
 * <li>/nvwa-utils/xml/decoder?id=123&json_data=bbb</li>
 * <li>id=123&json_data=bbb</li>
 * </li>
 * </ul>
 * @param cls
 * @return
 * @throws Exception 
 */
public static <T> T decode(String url, Class<T> cls) throws Exception {
    if (StringUtils.isBlank(url))
        return null;
    T t = cls.newInstance();

    String string = null;
    if (StringUtils.contains(url, "?")) {
        string = StringUtils.substringAfter(url, "?");
    } else {
        int start = StringUtils.indexOf(url, "?") + 1;
        string = StringUtils.substring(url, start);
    }

    Map<String, Object> attrs = Maps.newHashMap();
    String[] kvs = StringUtils.split(string, "&");
    for (String kv : kvs) {
        String[] entry = StringUtils.split(kv, "=");
        if (entry.length <= 1) {
            continue;
        } else if (entry.length == 2) {
            attrs.put(entry[0], entry[1]);
        } else {
            List<String> s = Lists.newArrayList(entry);
            s.remove(0);
            attrs.put(entry[0], StringUtils.join(s.toArray(new String[0]), "="));
        }
    }

    Field[] fields = cls.getDeclaredFields();
    for (Field field : fields) {
        // if the field name is 'appId'
        String fieldName = field.getName();
        String paramName = fieldName;
        if (field.isAnnotationPresent(Argument.class)) {
            paramName = field.getAnnotation(Argument.class).name();
        }
        // select appId node
        Object current = attrs.get(paramName);
        if (null == current) {
            // select appid node
            current = attrs.get(paramName.toLowerCase());
        }
        if (null == current) {
            // select APPID node
            current = attrs.get(paramName.toUpperCase());
        }
        if (null == current) {
            // select app_id node
            String nodename = StringUtils.join(StringUtils.splitByCharacterTypeCamelCase(paramName), "_")
                    .toLowerCase();
            current = attrs.get(nodename);
        }
        if (null == current) {
            // select APP_ID node
            String nodename = StringUtils.join(StringUtils.splitByCharacterTypeCamelCase(paramName), "_")
                    .toUpperCase();
            current = attrs.get(nodename);
        }
        if (null != current) {
            String invokeName = StringUtils.join(new String[] { "set", StringUtils.capitalize(fieldName) });
            try {
                MethodUtils.invokeMethod(t, invokeName, current);
            } catch (NoSuchMethodException e) {
                LOGGER.warn("NoSuchMethod-" + invokeName);
            } catch (IllegalAccessException e) {
                LOGGER.warn("IllegalAccess-" + invokeName);
            } catch (InvocationTargetException e) {
                LOGGER.warn("InvocationTarget-" + invokeName);
            }
        }
    }
    return t;
}

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

/**
 * Fetches the fields 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 fields are examined, including protected and private fields.
 * If a field 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 fields
 * @return the collection of methods with the annotation
 *//*  ww w .ja va 2  s.c om*/
protected static Collection<Field> getFields(Class<?> clazz) {
    Collection<Field> fields = fieldMap.get(clazz);
    if (fields == null) {
        fields = ReflectUtil.getFields(clazz);
        Iterator<Field> iterator = fields.iterator();

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

        fieldMap.put(clazz, fields);
    }

    return fields;
}

From source file:net.minecraftforge.common.config.ConfigManager.java

private static String getName(Field f) {
    if (f.isAnnotationPresent(Name.class))
        return f.getAnnotation(Name.class).value();
    return f.getName();
}

From source file:com.linkedin.pinot.perf.QueryRunner.java

private static void printUsage() {
    System.out.println("Usage: QueryRunner");
    for (Field field : QueryRunner.class.getDeclaredFields()) {
        if (field.isAnnotationPresent(Option.class)) {
            Option option = field.getAnnotation(Option.class);
            System.out.println(String.format("\t%-15s: %s (required=%s)", option.name(), option.usage(),
                    option.required()));
        }// w  ww.  j av  a 2s  .  c  o m
    }
}

From source file:org.agiso.core.lang.util.ObjectUtils.java

/**
 * Generuje sum haszujc obiektu wykorzystujc mechamizmy refleksji.
 * Podczas jej wyznaczania wykorzystuje opis dostarczany przez adnotacj
 * {@link InHashCode}. Ignoruje pola finalne oraz statyczne.
 * //from  www.j  av  a  2 s . c o  m
 * @see HashCodeBuilder#reflectionHashCode(Object, String[])
 */
public static int hashCodeBuilder(Object object) {
    Set<String> excludeFields = new HashSet<String>();
    for (Field field : object.getClass().getDeclaredFields()) {
        if (field.isAnnotationPresent(InHashCode.class)) {
            InHashCode inHashCode = field.getAnnotation(InHashCode.class);
            if (inHashCode.ignore()) {
                excludeFields.add(field.getName());
            }
        }
    }
    return HashCodeBuilder.reflectionHashCode(object, excludeFields);
}

From source file:org.agiso.core.lang.util.ObjectUtils.java

/**
 * Porwnuje dwa obiekty wykorzystujc mechamizmy refleksji. W trakcie
 * porwnywania wykorzystuje opis dostarczany przez adnotacj {@link
 * InEquals}. Ignoruje pola finalne oraz statyczne.
 * //from ww  w  .  j  av  a2  s  .c o  m
 * @see EqualsBuilder#reflectionEquals(Object, Object, String[])
 */
public static boolean equalsBuilder(Object object1, Object object2) {
    Set<String> excludeFields = new HashSet<String>();
    for (Field field : object1.getClass().getDeclaredFields()) {
        if (field.isAnnotationPresent(InEquals.class)) {
            InEquals inEquals = field.getAnnotation(InEquals.class);
            if (inEquals.ignore()) {
                excludeFields.add(field.getName());
            }
        }
    }
    return EqualsBuilder.reflectionEquals(object1, object2, excludeFields);
}

From source file:com.linkedin.pinot.tools.segment.converter.DictionaryToRawIndexConverter.java

/**
 * Helper method to print usage at the command line interface.
 *///from   www.  jav a2s  . c o m
private static void printUsage() {
    System.out.println("Usage: DictionaryTORawIndexConverter");
    for (Field field : ColumnarToStarTreeConverter.class.getDeclaredFields()) {

        if (field.isAnnotationPresent(Option.class)) {
            Option option = field.getAnnotation(Option.class);

            System.out.println(String.format("\t%-15s: %s (required=%s)", option.name(), option.usage(),
                    option.required()));
        }
    }
}

From source file:com.pmarlen.model.controller.EntityJPAToPlainPojoTransformer.java

public static void copyPlainValues(Entity entity, Object plain) {
    final Class entityClass;
    entityClass = entity.getClass();/*from w ww.ja  v  a 2s. c o m*/
    final String entityClassName = entityClass.getName();
    Hashtable<String, Object> propertiesToCopy = new Hashtable<String, Object>();
    Hashtable<String, Object> propertiesM2MToCopy = new Hashtable<String, Object>();
    List<String> propertiesWithNULLValueToCopy = new ArrayList<String>();
    List<String> propertiesKey = new ArrayList<String>();
    try {
        final Field[] declaredFields = entityClass.getDeclaredFields();
        for (Field f : declaredFields) {
            logger.trace("->create: \tcopy: " + entityClassName + "." + f.getName() + " accesible ? "
                    + (f.isAccessible()));
            if (!f.isAccessible()) {

                if (f.isAnnotationPresent(javax.persistence.Id.class)) {
                    propertiesKey.add(f.getName());
                }
                if (f.isAnnotationPresent(javax.persistence.Id.class)
                        && !f.isAnnotationPresent(javax.persistence.GeneratedValue.class)
                        && !Modifier.isStatic(f.getModifiers())) {

                    Object valueCopyed = PropertyUtils.getProperty(entity, f.getName());
                    if (valueCopyed != null) {
                        propertiesToCopy.put(f.getName(), valueCopyed);
                    } else {
                        propertiesWithNULLValueToCopy.add(f.getName());
                    }
                    logger.trace("->create:\t\t ID elegible 2 be copied, added to copy list: " + f.getName()
                            + " = " + valueCopyed + ", is really null?" + (valueCopyed == null));
                } else if (!f.isAnnotationPresent(javax.persistence.Id.class)
                        && !f.isAnnotationPresent(javax.persistence.OneToMany.class)
                        && !f.isAnnotationPresent(javax.persistence.ManyToMany.class)
                        && !Modifier.isStatic(f.getModifiers())) {

                    Object valueCopyed = PropertyUtils.getProperty(entity, f.getName());
                    if (valueCopyed != null) {
                        propertiesToCopy.put(f.getName(), valueCopyed);
                    } else {
                        propertiesWithNULLValueToCopy.add(f.getName());
                    }
                    logger.trace("->create:\t\t elegible 2 be copied, added to copy list: " + f.getName()
                            + " = " + valueCopyed + ", is really null?" + (valueCopyed == null));
                } else if (!f.isAnnotationPresent(javax.persistence.Id.class)
                        && f.isAnnotationPresent(javax.persistence.ManyToMany.class)) {

                    Object valueCopyed = PropertyUtils.getProperty(entity, f.getName());
                    if (valueCopyed != null) {
                        propertiesM2MToCopy.put(f.getName(), valueCopyed);
                    } else {
                        propertiesWithNULLValueToCopy.add(f.getName());
                    }
                    logger.trace("->create:\t\t M2M elegible 2 be copied, added to copy list: " + f.getName()
                            + " = " + valueCopyed + ", is really null?" + (valueCopyed == null));
                }
            }
        }
        logger.trace("->create:copy values ?");
        for (String p2c : propertiesToCopy.keySet()) {
            Object valueCopyed = propertiesToCopy.get(p2c);
            logger.trace("->create:\t\t copy value with SpringUtils: " + p2c + " = " + valueCopyed
                    + ", is null?" + (valueCopyed == null));
            BeanUtils.copyProperty(plain, p2c, valueCopyed);
        }
        for (String p2c : propertiesWithNULLValueToCopy) {
            logger.trace("->create:\t\t copy null with SpringUtils");
            BeanUtils.copyProperty(plain, p2c, null);
        }
    } catch (Exception e) {
        logger.error("..in copy", e);
    }
}

From source file:ambroafb.general.AnnotiationUtils.java

public static boolean everyFieldContentIsValidFor(Object currentClassObject,
        EditorPanel.EDITOR_BUTTON_TYPE type) {
    boolean result = true;
    Field[] fields = currentClassObject.getClass().getDeclaredFields();

    for (Field field : fields) {
        if (field.isAnnotationPresent(Annotations.ContentNotEmpty.class)) {
            result = result && checkValidationForIsNotEmptyAnnotation(field, currentClassObject);
        }/* w  ww .j a  v a2  s.  c  o  m*/
        if (field.isAnnotationPresent(Annotations.ContentMail.class)) {
            result = result && checkValidationForContentMailAnnotation(field, currentClassObject);
        }
        if (field.isAnnotationPresent(Annotations.ContentTreeItem.class)) {
            result = result && checkValidationForContentTreeItemAnnotation(field, currentClassObject, type);
        }
        if (field.isAnnotationPresent(Annotations.ContentRate.class)) {
            result = result && checkValidationForContentRateAnnotation(field, currentClassObject);
        }
        if (field.isAnnotationPresent(Annotations.ContentAmount.class)) {
            result = result && checkValidationForContentAmountAnnotation(field, currentClassObject);
        }
        if (field.isAnnotationPresent(Annotations.ContentISO.class)) {
            result = result && checkValidationForContentISOAnnotation(field, currentClassObject);
        }
        if (field.isAnnotationPresent(Annotations.ContentPattern.class)) {
            result = result && checkValidationForContentPatternAnnotation(field, currentClassObject);
        }
        if (field.isAnnotationPresent(Annotations.ContentMapEditor.class)) {
            result = result && checkValidationForContentMapEditorAnnotation(field, currentClassObject);
        }
    }
    return result;
}