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:br.gov.frameworkdemoiselle.util.contrib.Reflections.java

public static Field getAnnotatedField(Class<?> clazz, Class<? extends Annotation> aclazz, boolean required)
        throws Exception {
    for (Field field : getSuperClassesFields(clazz))
        if (field.isAnnotationPresent(aclazz))
            return field;
    if (required)
        throw new Exception(
                "Field with @" + aclazz.getSimpleName() + " not found on class " + clazz.getSimpleName());
    else/*w w  w . j a v  a2  s  .c  om*/
        return null;
}

From source file:jp.co.opentone.bsol.framework.web.view.PagePropertyUtil.java

/**
 * page??{@link Transfer}????????.//from   w w w  .  j  av a2  s .  c  om
 * <p>
 * ???????????????.
 * </p>
 * @param page
 *            page
 * @return {@link Transfer}????
 */
public static Map<String, Object> collectTransferValues(Page page) {
    Map<String, Object> values = new HashMap<String, Object>();

    for (Class<?> c = page.getClass(); c != null; c = c.getSuperclass()) {
        for (Field field : c.getDeclaredFields()) {
            if (field.isAnnotationPresent(Transfer.class)) {
                String name = field.getName();
                Object value;
                try {
                    value = PropertyUtils.getProperty(page, name);
                    if (value != null) {
                        values.put(name, value);
                    }
                } catch (IllegalAccessException e) {
                    throw new ReflectionRuntimeException(e);
                } catch (InvocationTargetException e) {
                    throw new ReflectionRuntimeException(e);
                } catch (NoSuchMethodException e) {
                    throw new ReflectionRuntimeException(e);
                }
            }
        }
    }
    return values;
}

From source file:com.opencsv.bean.MappingUtils.java

/**
 * Determines which mapping strategy is appropriate for this bean.
 * The algorithm is:<ol>/*from   www. ja  v a  2s  .  co m*/
 * <li>If annotations {@link CsvBindByPosition} or
 * {@link CsvCustomBindByPosition} are present,
 * {@link ColumnPositionMappingStrategy} is chosen.</li>
 * <li>Otherwise, {@link HeaderColumnNameMappingStrategy} is chosen. If
 * annotations are present, they will be used, otherwise the field names
 * will be used as the column names.</li></ol>
 * 
 * @param <T> The type of the bean for which the mapping strategy is sought
 * @param type The class of the bean for which the mapping strategy is sought
 * @return A functional mapping strategy for the bean in question
 */
public static <T> MappingStrategy<T> determineMappingStrategy(Class type) {
    // Check for annotations
    Field[] fields = FieldUtils.getAllFields(type);
    boolean positionAnnotationsPresent = false;
    for (Field field : fields) {
        if (field.isAnnotationPresent(CsvBindByPosition.class)
                || field.isAnnotationPresent(CsvCustomBindByPosition.class)) {
            positionAnnotationsPresent = true;
            break;
        }
        if (positionAnnotationsPresent) {
            break;
        }
    }

    // Set the mapping strategy according to what we've found.
    MappingStrategy<T> mappingStrategy;
    if (positionAnnotationsPresent) {
        ColumnPositionMappingStrategy<T> ms = new ColumnPositionMappingStrategy<T>();
        ms.setType(type);
        mappingStrategy = ms;
    } else {
        HeaderColumnNameMappingStrategy<T> ms = new HeaderColumnNameMappingStrategy<T>();
        ms.setType(type);

        // Ugly hack, but I have to get the field names into the stupid
        // strategy somehow.
        if (!ms.isAnnotationDriven()) {
            SortedSet<String> sortedFields = new TreeSet<String>();
            for (Field f : fields) {
                if (!f.isSynthetic()) { // Otherwise JaCoCo breaks tests
                    sortedFields.add(f.getName());
                }
            }
            String header = StringUtils.join(sortedFields, ',').concat("\n");
            try {
                ms.captureHeader(new CSVReader(new StringReader(header)));
                ms.findDescriptor(0);
            } catch (IOException e) {
                // Can't happen. It's a StringReader with a defined string.
            } catch (IntrospectionException e) {
                CsvBeanIntrospectionException csve = new CsvBeanIntrospectionException("");
                csve.initCause(e);
                throw csve;
            }
        }

        mappingStrategy = ms;
    }
    return mappingStrategy;
}

From source file:com.bosscs.spark.commons.utils.AnnotationUtils.java

/**
 * Utility method that filters out all the fields _not_ annotated
 * with the {@link com.bosscs.spark.commons.annotations.HadoopField} annotation.
 *
 * @param clazz the Class object for which we want to resolve deep fields.
 * @return an array of deep Field(s).//from   ww w .  j av a  2  s .  c o  m
 */
public static Field[] filterDeepFields(Class clazz) {
    Field[] fields = Utils.getAllFields(clazz);
    List<Field> filtered = new ArrayList<>();
    for (Field f : fields) {
        if (f.isAnnotationPresent(HadoopField.class)) {
            filtered.add(f);
        }
    }
    return filtered.toArray(new Field[filtered.size()]);
}

From source file:com.stratio.deep.commons.utils.AnnotationUtils.java

/**
 * Utility method that filters out all the fields _not_ annotated
 * with the {@link com.stratio.deep.commons.annotations.DeepField} annotation.
 *
 * @param clazz the Class object for which we want to resolve deep fields.
 * @return an array of deep Field(s).//  w  ww . j a v a2 s. c  o  m
 */
public static Field[] filterDeepFields(Class clazz) {
    Field[] fields = Utils.getAllFields(clazz);
    List<Field> filtered = new ArrayList<>();
    for (Field f : fields) {
        if (f.isAnnotationPresent(DeepField.class)) {
            filtered.add(f);
        }
    }
    return filtered.toArray(new Field[filtered.size()]);
}

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

public static String encode(Object obj, String jointChar, boolean sort, Comparator<String> comparator) {
    StringBuilder rst = new StringBuilder();
    List<String> list = Lists.newArrayList();
    Field[] fields = obj.getClass().getDeclaredFields();
    for (Field field : fields) {
        String fieldName = field.getName();
        String paramName = fieldName;
        if (field.isAnnotationPresent(Argument.class)) {
            paramName = field.getAnnotation(Argument.class).name();
        }/*from   w w w. j av  a  2  s  . c  o m*/
        String invokeName = StringUtils.join(new String[] { "get", StringUtils.capitalize(fieldName) });
        try {
            Object value = MethodUtils.invokeMethod(obj, invokeName, new Object[0]);
            if (null != value)
                list.add(StringUtils.join(new String[] { paramName, String.valueOf(value) }, "="));
        } catch (NoSuchMethodException e) {
            LOGGER.warn("NoSuchMethod-" + invokeName);
        } catch (IllegalAccessException e) {
            LOGGER.warn("IllegalAccess-" + invokeName);
        } catch (InvocationTargetException e) {
            LOGGER.warn("InvocationTarget-" + invokeName);
        }
    }
    if (sort)
        Collections.sort(list, (null != comparator) ? comparator : String.CASE_INSENSITIVE_ORDER);

    for (String item : list) {
        rst.append(item).append(jointChar);
    }
    return StringUtils.removeEnd(rst.toString(), jointChar);
}

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

/**
 * Helper method to print usage at the command line interface.
 *//*from  w  ww .j ava 2 s  . com*/
private static void printUsage() {
    System.out.println("Usage: ColumnarToStarTreeConverter");
    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.searchbox.core.ref.ReflectionUtils.java

public static void inspectAndSaveAttribute(Class<?> searchElement, Collection<AttributeEntity> attributes) {
    if (searchElement != null) {
        for (Field field : searchElement.getDeclaredFields()) {
            if (field.isAnnotationPresent(SearchAttribute.class)) {
                AttributeEntity attrDef = new AttributeEntity().setName(field.getName())
                        .setType(field.getType());
                String value = field.getAnnotation(SearchAttribute.class).value();
                if (value != null && !value.isEmpty()) {
                    try {
                        Object ovalue = BeanUtils.instantiateClass(field.getType().getConstructor(String.class),
                                value);/*from w  w w .  ja  v a 2  s  .co  m*/
                        attrDef.setValue(ovalue);
                    } catch (BeanInstantiationException | NoSuchMethodException | SecurityException e) {
                        LOGGER.trace("Could not construct default value (not much of a problem)", e);
                    }
                }
                attributes.add(attrDef);
            }
        }
        inspectAndSaveAttribute(searchElement.getSuperclass(), attributes);
    } else {
        return;
    }
}

From source file:com.epam.ta.reportportal.database.search.CriteriaMap.java

public static String getQueryCriteria(Field f) {
    String queryCriteria;/*from www.ja v  a  2  s  .co  m*/
    if (f.isAnnotationPresent(org.springframework.data.mongodb.core.mapping.Field.class)) {
        queryCriteria = f.getAnnotation(org.springframework.data.mongodb.core.mapping.Field.class).value();
    } else {
        queryCriteria = f.getName();
    }
    return queryCriteria;
}

From source file:com.example.captain_miao.grantap.utils.PermissionUtils.java

public static <A extends Annotation> String[] findPermissionsWithRequestCode(Object object, Class clazz,
        Class<A> annotation, int requestCode) {
    Field[] fields = clazz.getDeclaredFields();
    for (Field field : fields) {
        if (field.isAnnotationPresent(annotation)) {
            if (isEqualRequestCodeFromAnnotation(field, annotation, requestCode)) {
                field.setAccessible(true);
                try {
                    return (String[]) field.get(object);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }//from w w w  .j  a va 2 s .co  m
            }
        }
    }
    return null;
}