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:me.anon.lib.Views.java

/**
 * Resets all @InjectView annotated members to null.
 * Use this in the `onDestroyView()` of your fragment
 * @param target The target class//from   www  .jav a  2s. c  om
 */
public static void reset(Object target) {
    ArrayList<Field> fields = new ArrayList<Field>();
    Class objOrSuper = target.getClass();

    if (!objOrSuper.isAnnotationPresent(Injectable.class)) {
        Log.e("InjectView", "No Injectable annotation for class " + objOrSuper);
        return;
    }

    while (objOrSuper.isAnnotationPresent(Injectable.class)) {
        for (Field field : objOrSuper.getDeclaredFields()) {
            if (field.isAnnotationPresent(InjectView.class)
                    || field.isAnnotationPresent(InjectFragment.class)) {
                fields.add(field);
            }
        }

        objOrSuper = objOrSuper.getSuperclass();
    }

    for (Field field : fields) {
        Annotation annotation = field.getAnnotation(InjectView.class);

        if (annotation == null) {
            annotation = field.getAnnotation(InjectFragment.class);
        }

        if (annotation != null) {
            try {
                field.setAccessible(true);
                field.set(target, null);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:com.madrobot.di.Converter.java

public static void storeValue(final JSONObject jsonObject, final String key, Object value, final Field field)
        throws JSONException {

    Class<?> classType = field.getType();

    if (clzTypeKeyMap.containsKey(classType)) {
        final int code = clzTypeKeyMap.get(classType);
        switch (code) {
        case TYPE_STRING:
        case TYPE_SHORT:
        case TYPE_INT:
        case TYPE_LONG:
        case TYPE_CHAR:
        case TYPE_FLOAT:
        case TYPE_DOUBLE:
            break;
        case TYPE_BOOLEAN:
            Boolean userValue = (Boolean) value;
            if (field.isAnnotationPresent(BooleanFormat.class)) {
                BooleanFormat formatAnnotation = field.getAnnotation(BooleanFormat.class);
                String trueFormat = formatAnnotation.trueFormat();
                String falseFormat = formatAnnotation.falseFormat();
                if (userValue) {
                    value = trueFormat;/* w w w.ja v a2 s . com*/
                } else {
                    value = falseFormat;
                }
            } else {
                value = userValue;
            }
            break;
        case TYPE_DATE:
            Date date = (Date) value;
            SimpleDateFormat simpleDateFormat = null;
            if (field.isAnnotationPresent(com.madrobot.di.wizard.json.annotations.DateFormat.class)) {
                com.madrobot.di.wizard.json.annotations.DateFormat formatAnnotation = field
                        .getAnnotation(com.madrobot.di.wizard.json.annotations.DateFormat.class);
                String dateFormat = formatAnnotation.format();
                simpleDateFormat = new SimpleDateFormat(dateFormat);
            } else {
                simpleDateFormat = new SimpleDateFormat();
            }
            value = simpleDateFormat.format(date);
            break;
        }
        jsonObject.put(key, value);
    }
}

From source file:gr.abiss.calipso.jpasearch.json.serializer.FormSchemaSerializer.java

private static String getFormFieldConfig(Class domainClass, String fieldName) {
    String formSchemaJson = null;
    Field field = null;
    StringBuffer formConfig = new StringBuffer();
    String key = domainClass.getName() + "#" + fieldName;
    String cached = CONFIG_CACHE.get(key);
    if (StringUtils.isNotBlank(cached)) {
        formConfig.append(cached);/*from  w  w w . ja v  a  2 s .  c o  m*/
    } else {
        Class tmpClass = domainClass;
        do {
            for (Field tmpField : tmpClass.getDeclaredFields()) {
                String candidateName = tmpField.getName();
                if (candidateName.equals(fieldName)) {
                    field = tmpField;
                    FormSchemas formSchemasAnnotation = null;
                    if (field.isAnnotationPresent(FormSchemas.class)) {
                        formSchemasAnnotation = field.getAnnotation(FormSchemas.class);
                        gr.abiss.calipso.jpasearch.annotation.FormSchemaEntry[] formSchemas = formSchemasAnnotation
                                .value();
                        LOGGER.info("getFormFieldConfig, formSchemas: " + formSchemas);
                        if (formSchemas != null) {
                            for (int i = 0; i < formSchemas.length; i++) {
                                if (i > 0) {
                                    formConfig.append(comma);
                                }
                                gr.abiss.calipso.jpasearch.annotation.FormSchemaEntry formSchemaAnnotation = formSchemas[i];
                                LOGGER.info(
                                        "getFormFieldConfig, formSchemaAnnotation: " + formSchemaAnnotation);
                                appendFormFieldSchema(formConfig, formSchemaAnnotation.state(),
                                        formSchemaAnnotation.json());
                            }
                        }
                        //formConfig = formSchemasAnnotation.json();
                    } else {
                        appendFormFieldSchema(formConfig,
                                gr.abiss.calipso.jpasearch.annotation.FormSchemaEntry.STATE_DEFAULT,
                                gr.abiss.calipso.jpasearch.annotation.FormSchemaEntry.TYPE_STRING);
                    }
                    break;
                }
            }
            tmpClass = tmpClass.getSuperclass();
        } while (tmpClass != null && field == null);
        formSchemaJson = formConfig.toString();
        CONFIG_CACHE.put(key, formSchemaJson);
    }

    return formSchemaJson;
}

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

private static void sync(Configuration cfg, Class<?> cls, String modid, String category, boolean loading,
        Object instance) {/*from   w  ww .  ja  v a2 s  .co  m*/
    for (Field f : cls.getDeclaredFields()) {
        if (!Modifier.isPublic(f.getModifiers()))
            continue;

        //Only the root class may have static fields. Otherwise category tree nodes of the same type would share the
        //contained value messing up the sync
        if (Modifier.isStatic(f.getModifiers()) != (instance == null))
            continue;

        if (f.isAnnotationPresent(Config.Ignore.class))
            continue;

        String comment = null;
        Comment ca = f.getAnnotation(Comment.class);
        if (ca != null)
            comment = NEW_LINE.join(ca.value());

        String langKey = modid + "." + (category.isEmpty() ? "" : category + Configuration.CATEGORY_SPLITTER)
                + f.getName().toLowerCase(Locale.ENGLISH);
        LangKey la = f.getAnnotation(LangKey.class);
        if (la != null)
            langKey = la.value();

        boolean requiresMcRestart = f.isAnnotationPresent(Config.RequiresMcRestart.class);
        boolean requiresWorldRestart = f.isAnnotationPresent(Config.RequiresWorldRestart.class);

        if (FieldWrapper.hasWrapperFor(f)) //Wrappers exist for primitives, enums, maps and arrays
        {
            if (Strings.isNullOrEmpty(category))
                throw new RuntimeException(
                        "An empty category may not contain anything but objects representing categories!");
            try {
                IFieldWrapper wrapper = FieldWrapper.get(instance, f, category);
                ITypeAdapter adapt = wrapper.getTypeAdapter();
                Property.Type propType = adapt.getType();

                for (String key : wrapper.getKeys()) //Iterate the fully qualified property names the field provides
                {
                    String suffix = StringUtils.replaceOnce(key,
                            wrapper.getCategory() + Configuration.CATEGORY_SPLITTER, "");

                    boolean existed = exists(cfg, wrapper.getCategory(), suffix);
                    if (!existed || loading) //Creates keys in category specified by the wrapper if new ones are programaticaly added
                    {
                        Property property = property(cfg, wrapper.getCategory(), suffix, propType,
                                adapt.isArrayAdapter());

                        adapt.setDefaultValue(property, wrapper.getValue(key));
                        if (!existed)
                            adapt.setValue(property, wrapper.getValue(key));
                        else
                            wrapper.setValue(key, adapt.getValue(property));
                    } else //If the key is not new, sync according to shouldReadFromVar()
                    {
                        Property property = property(cfg, wrapper.getCategory(), suffix, propType,
                                adapt.isArrayAdapter());
                        Object propVal = adapt.getValue(property);
                        Object mapVal = wrapper.getValue(key);
                        if (shouldReadFromVar(property, propVal, mapVal))
                            adapt.setValue(property, mapVal);
                        else
                            wrapper.setValue(key, propVal);
                    }
                }

                ConfigCategory confCat = cfg.getCategory(wrapper.getCategory());

                for (Property property : confCat.getOrderedValues()) //Iterate the properties to check for new data from the config side
                {
                    String key = confCat.getQualifiedName() + Configuration.CATEGORY_SPLITTER
                            + property.getName();
                    if (!wrapper.handlesKey(key))
                        continue;

                    if (loading || !wrapper.hasKey(key)) {
                        Object value = wrapper.getTypeAdapter().getValue(property);
                        wrapper.setValue(key, value);
                    }
                }

                if (loading)
                    wrapper.setupConfiguration(cfg, comment, langKey, requiresMcRestart, requiresWorldRestart);

            } catch (Exception e) {
                String format = "Error syncing field '%s' of class '%s'!";
                String error = String.format(format, f.getName(), cls.getName());
                throw new RuntimeException(error, e);
            }
        } else if (f.getType().getSuperclass() != null && f.getType().getSuperclass().equals(Object.class)) { //If the field extends Object directly, descend the object tree and access the objects members
            Object newInstance = null;
            try {
                newInstance = f.get(instance);
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            }

            //Setup the sub category with its respective name, comment, language key, etc.
            String sub = (category.isEmpty() ? "" : category + Configuration.CATEGORY_SPLITTER)
                    + getName(f).toLowerCase(Locale.ENGLISH);
            ConfigCategory confCat = cfg.getCategory(sub);
            confCat.setComment(comment);
            confCat.setLanguageKey(langKey);
            confCat.setRequiresMcRestart(requiresMcRestart);
            confCat.setRequiresWorldRestart(requiresWorldRestart);

            sync(cfg, f.getType(), modid, sub, loading, newInstance);
        } else {
            String format = "Can't handle field '%s' of class '%s': Unknown type.";
            String error = String.format(format, f.getName(), cls.getCanonicalName());
            throw new RuntimeException(error);
        }
    }
}

From source file:com.github.hateoas.forms.spring.SpringActionDescriptor.java

private static Field getFormAnnotated(final String fieldName, Class<?> entity) throws NoSuchFieldException {
    while (entity != null) {
        try {//from w  w  w. j  a v a  2 s . c  om
            Field field = entity.getDeclaredField(fieldName);
            field.setAccessible(true);
            if (field.isAnnotationPresent(Select.class) || field.isAnnotationPresent(Input.class)) {
                return field;
            }
            break;
        } catch (NoSuchFieldException e) {
            entity = entity.getSuperclass();
        }
    }
    return null;
}

From source file:org.cleandroid.core.rest.JSONMapper.java

@SuppressWarnings("unchecked")
public static <T> T parseObject(String jsonString, Class<T> type) {
    try {//w  w  w.j av a 2  s  . c om
        JSONObject dataObject = new JSONObject(jsonString);
        T object = type.newInstance();
        for (Field f : type.getDeclaredFields()) {
            f.setAccessible(true);
            Iterator<String> iterator = dataObject.keys();
            while (iterator.hasNext()) {
                String key = iterator.next();
                if (key.equals(f.getName())) {

                    if (Collection.class.isAssignableFrom(f.getType()))
                        f.set(object, parseCollection(dataObject.getJSONArray(key).toString(), f.getType()));
                    else {
                        if (dataObject.get(key) instanceof JSONObject)
                            f.set(object, parseObject(dataObject.getJSONObject(key).toString(), f.getType()));
                        else if (f.isAnnotationPresent(DateFormat.class))
                            f.set(object, TypeUtils.getTypedValue(dataObject.getString(key), f.getType(),
                                    f.getAnnotation(DateFormat.class).value()));
                        else
                            f.set(object, TypeUtils.getTypedValue(dataObject.getString(key), f.getType()));

                    }
                    break;
                }

            }
        }
        return object;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:cn.teamlab.wg.framework.util.csv.CsvWriter.java

/**
 * Bean?CSV?//w w w.ja  v  a  2  s  . c o  m
 * Bean@CsvPropAnno(index = ?)
 * @param objList
 * @return
 * @throws NoSuchMethodException 
 * @throws InvocationTargetException 
 * @throws IllegalAccessException 
 */
public static String bean2Csv(List<?> objList) throws Exception {
    if (objList == null || objList.size() == 0) {
        return "";
    }
    TreeMap<Integer, CsvFieldBean> map = new TreeMap<Integer, CsvFieldBean>();
    Object bean0 = objList.get(0);
    Class<?> clazz = bean0.getClass();

    PropertyDescriptor[] arr = org.springframework.beans.BeanUtils.getPropertyDescriptors(clazz);
    for (PropertyDescriptor p : arr) {
        String fieldName = p.getName();
        Field field = FieldUtils.getDeclaredField(clazz, fieldName, true);
        if (field == null) {
            continue;
        }

        boolean isAnno = field.isAnnotationPresent(CsvFieldAnno.class);
        if (isAnno) {
            CsvFieldAnno anno = field.getAnnotation(CsvFieldAnno.class);
            int idx = anno.index();
            map.put(idx, new CsvFieldBean(idx, anno.title(), fieldName));
        }
    }

    // CSVBuffer
    StringBuffer buff = new StringBuffer();

    // ???
    boolean withTitle = clazz.isAnnotationPresent(CsvTitleAnno.class);
    // ??csv
    if (withTitle) {
        StringBuffer titleBuff = new StringBuffer();
        for (int key : map.keySet()) {
            CsvFieldBean fieldBean = map.get(key);
            titleBuff.append(Letters.QUOTE).append(fieldBean.getTitle()).append(Letters.QUOTE);
            titleBuff.append(Letters.COMMA);
        }
        buff.append(StringUtils.chop(titleBuff.toString()));
        buff.append(Letters.LF);
        titleBuff.setLength(0);
    }

    for (Object o : objList) {
        StringBuffer tmpBuff = new StringBuffer();

        for (int key : map.keySet()) {
            CsvFieldBean fieldBean = map.get(key);

            Object val = BeanUtils.getProperty(o, fieldBean.getFieldName());
            if (val != null) {
                tmpBuff.append(Letters.QUOTE).append(val).append(Letters.QUOTE);
            } else {
                tmpBuff.append(StringUtils.EMPTY);
            }
            tmpBuff.append(Letters.COMMA);
        }

        buff.append(StringUtils.chop(tmpBuff.toString()));
        buff.append(Letters.LF);
        tmpBuff.setLength(0);
    }

    return buff.toString();
}

From source file:com.unboundid.scim2.common.utils.SchemaUtils.java

/**
 * Gets SCIM schema attributes for a class.
 *
 * @param classesProcessed a stack containing the classes processed prior
 *                         to this class.  This is used for cycle detection.
 * @param cls the class to get the attributes for.
 * @return a collection of SCIM schema attributes for the class.
 * @throws IntrospectionException thrown if an error occurs during
 *    Introspection.//from   w w w . j  av  a2  s. c o  m
 */
private static Collection<AttributeDefinition> getAttributes(final Stack<String> classesProcessed,
        final Class<?> cls) throws IntrospectionException {
    String className = cls.getCanonicalName();
    if (!cls.isAssignableFrom(AttributeDefinition.class) && classesProcessed.contains(className)) {
        throw new RuntimeException("Cycles detected in Schema");
    }

    Collection<PropertyDescriptor> propertyDescriptors = getPropertyDescriptors(cls);
    Collection<AttributeDefinition> attributes = new ArrayList<AttributeDefinition>();

    for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
        if (propertyDescriptor.getName().equals("subAttributes")
                && cls.isAssignableFrom(AttributeDefinition.class) && classesProcessed.contains(className)) {
            // Skip second nesting of subAttributes the second time around
            // since there is no subAttributes of subAttributes in SCIM.
            continue;
        }
        AttributeDefinition.Builder attributeBuilder = new AttributeDefinition.Builder();

        Field field = findField(cls, propertyDescriptor.getName());

        if (field == null) {
            continue;
        }
        Attribute schemaProperty = null;
        JsonProperty jsonProperty = null;
        if (field.isAnnotationPresent(Attribute.class)) {
            schemaProperty = field.getAnnotation(Attribute.class);
        }
        if (field.isAnnotationPresent(JsonProperty.class)) {
            jsonProperty = field.getAnnotation(JsonProperty.class);
        }

        // Only generate schema for annotated fields.
        if (schemaProperty == null) {
            continue;
        }

        addName(attributeBuilder, propertyDescriptor, jsonProperty);
        addDescription(attributeBuilder, schemaProperty);
        addCaseExact(attributeBuilder, schemaProperty);
        addRequired(attributeBuilder, schemaProperty);
        addReturned(attributeBuilder, schemaProperty);
        addUniqueness(attributeBuilder, schemaProperty);
        addReferenceTypes(attributeBuilder, schemaProperty);
        addMutability(attributeBuilder, schemaProperty);
        addMultiValued(attributeBuilder, propertyDescriptor, schemaProperty);
        addCanonicalValues(attributeBuilder, schemaProperty);

        Class propertyCls = propertyDescriptor.getPropertyType();

        // if this is a multivalued attribute the real sub attribute class is the
        // the one specified in the annotation, not the list, set, array, etc.
        if ((schemaProperty.multiValueClass() != NullType.class)) {
            propertyCls = schemaProperty.multiValueClass();
        }

        AttributeDefinition.Type type = getAttributeType(propertyCls);
        attributeBuilder.setType(type);

        if (type == AttributeDefinition.Type.COMPLEX) {
            // Add this class to the list to allow cycle detection
            classesProcessed.push(cls.getCanonicalName());
            Collection<AttributeDefinition> subAttributes = getAttributes(classesProcessed, propertyCls);
            attributeBuilder
                    .addSubAttributes(subAttributes.toArray(new AttributeDefinition[subAttributes.size()]));
            classesProcessed.pop();
        }

        attributes.add(attributeBuilder.build());
    }

    return attributes;
}

From source file:gr.abiss.calipso.uischema.serializer.UiSchemaSerializer.java

private static String getFormFieldConfig(Class domainClass, PropertyDescriptor descriptor, String fieldName) {
    String formSchemaJson = null;
    Field field = null;
    StringBuffer formConfig = new StringBuffer();
    String key = domainClass.getName() + "#" + fieldName;
    String cached = CONFIG_CACHE.get(key);
    if (StringUtils.isNotBlank(cached)) {
        formConfig.append(cached);//from w  ww.  j a  v a 2  s . c  o  m
    } else {
        Class tmpClass = domainClass;
        do {
            for (Field tmpField : tmpClass.getDeclaredFields()) {
                String candidateName = tmpField.getName();
                if (candidateName.equals(fieldName)) {
                    field = tmpField;
                    FormSchemas formSchemasAnnotation = null;
                    if (field.isAnnotationPresent(FormSchemas.class)) {
                        formSchemasAnnotation = field.getAnnotation(FormSchemas.class);
                        gr.abiss.calipso.uischema.annotation.FormSchemaEntry[] formSchemas = formSchemasAnnotation
                                .value();
                        LOGGER.info("getFormFieldConfig, formSchemas: " + formSchemas);
                        if (formSchemas != null) {
                            for (int i = 0; i < formSchemas.length; i++) {
                                if (i > 0) {
                                    formConfig.append(comma);
                                }
                                gr.abiss.calipso.uischema.annotation.FormSchemaEntry formSchemaAnnotation = formSchemas[i];
                                LOGGER.info(
                                        "getFormFieldConfig, formSchemaAnnotation: " + formSchemaAnnotation);
                                appendFormFieldSchema(formConfig, formSchemaAnnotation.state(),
                                        formSchemaAnnotation.json());
                            }
                        }
                        //formConfig = formSchemasAnnotation.json();
                    } else {
                        appendFormFieldSchema(formConfig,
                                gr.abiss.calipso.uischema.annotation.FormSchemaEntry.STATE_DEFAULT,
                                gr.abiss.calipso.uischema.annotation.FormSchemaEntry.TYPE_STRING);
                    }
                    break;
                }
            }
            tmpClass = tmpClass.getSuperclass();
        } while (tmpClass != null && field == null);
        formSchemaJson = formConfig.toString();
        CONFIG_CACHE.put(key, formSchemaJson);
    }

    return formSchemaJson;
}

From source file:com.seer.datacruncher.utils.generic.CommonUtils.java

/**
 * Method recursively iterate all fields
 * @throws IllegalAccessException//from  w ww  . ja v  a  2  s.  c o m
 * @throws IllegalArgumentException
 */
private static void recursiveIterateObjectWithXPath(Object obj, String strXPath, List<String> xPath,
        int location, Map<String, String> map) throws IllegalArgumentException, IllegalAccessException {
    if (obj == null)
        return;
    if (location > xPath.size())
        return;
    Field fields[] = obj.getClass().getDeclaredFields();
    for (Field f : fields) {
        f.setAccessible(true);
        String xmlElement = null;
        String xmlElementRef = null;
        String xmlAttribute = null;
        if (f.isAnnotationPresent(XmlElement.class)) {
            xmlElement = f.getAnnotation(XmlElement.class).name();
        } else if (f.isAnnotationPresent(XmlElementRef.class)) {
            xmlAttribute = f.getAnnotation(XmlElementRef.class).name();
        } else if (f.isAnnotationPresent(XmlAttribute.class)) {
            xmlAttribute = f.getAnnotation(XmlAttribute.class).name();
        }

        if (xPath.get(location).equals(xmlElement) || xPath.get(location).equals(f.getName())
                || xPath.get(location).equals(xmlElementRef) || xPath.get(location).equals(xmlAttribute)) {
            Object fieldObject = f.get(obj);
            if (location + 1 == xPath.size()) {
                if (fieldObject instanceof JAXBElement) {
                    map.put(strXPath, "" + ((JAXBElement<?>) fieldObject).getValue());
                } else {
                    if (fieldObject != null)
                        map.put(strXPath, fieldObject.toString());
                }
                return;
            } else {
                if (f.get(obj) instanceof List) {
                    for (Object o : (List<?>) f.get(obj)) {
                        recursiveIterateObjectWithXPath(o, strXPath, xPath, location + 1, map);
                    }
                } else {
                    recursiveIterateObjectWithXPath(f.get(obj), strXPath, xPath, location + 1, map);
                }
            }
        }
    }
}