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:microsoft.exchange.webservices.data.core.EwsUtilities.java

/**
 * Builds the enum to schema mapping dictionary.
 *
 * @param c class type//from w  w  w  .  j av a  2  s . c  om
 * @return The mapping from enum to schema name
 */
private static Map<String, String> buildEnumToSchemaDict(Class<?> c) {
    Map<String, String> dict = new HashMap<String, String>();
    Field[] fields = c.getFields();
    for (Field f : fields) {
        if (f.isEnumConstant() && f.isAnnotationPresent(EwsEnum.class)) {
            EwsEnum ewsEnum = f.getAnnotation(EwsEnum.class);
            String fieldName = f.getName();
            String schemaName = ewsEnum.schemaName();
            if (!schemaName.isEmpty()) {
                dict.put(fieldName, schemaName);
            }
        }
    }
    return dict;
}

From source file:microsoft.exchange.webservices.data.core.EwsUtilities.java

/**
 * Builds the schema to enum mapping dictionary.
 *
 * @param <E> Type of the enum.//from   www. j a  v a 2 s  . c  om
 * @param c   Class
 * @return The mapping from enum to schema name
 */
private static <E extends Enum<E>> Map<String, String> buildSchemaToEnumDict(Class<E> c) {
    Map<String, String> dict = new HashMap<String, String>();

    Field[] fields = c.getDeclaredFields();
    for (Field f : fields) {
        if (f.isEnumConstant() && f.isAnnotationPresent(EwsEnum.class)) {
            EwsEnum ewsEnum = f.getAnnotation(EwsEnum.class);
            String fieldName = f.getName();
            String schemaName = ewsEnum.schemaName();
            if (!schemaName.isEmpty()) {
                dict.put(schemaName, fieldName);
            }
        }
    }
    return dict;
}

From source file:com.qmetry.qaf.automation.ui.webdriver.ElementFactory.java

private boolean hasAnnotation(Field field, Class<? extends Annotation>... classes) {
    for (Class<? extends Annotation> cls : classes) {
        if (field.isAnnotationPresent(cls)) {
            return true;
        }//from   ww w.ja  v  a  2s. co  m
    }
    return false;
}

From source file:code.elix_x.excore.utils.nbt.mbt.encoders.NBTClassEncoder.java

public void populate(MBT mbt, NBTTagCompound nbt, Object o) {
    Class clazz = o.getClass();/*from w  w w  . java 2 s . c o  m*/
    try {
        while (clazz != null && clazz != Object.class) {
            if (!clazz.isAnnotationPresent(MBTIgnore.class)) {
                for (Field field : clazz.getDeclaredFields()) {
                    if (!field.isAnnotationPresent(MBTIgnore.class)) {
                        field.setAccessible(true);
                        if (nbt.hasKey(field.getName())) {
                            if (encodeStatic || !Modifier.isStatic(field.getModifiers())) {
                                if (Modifier.isFinal(field.getModifiers())) {
                                    if (encodeFinal) {
                                        Field modifiers = Field.class.getDeclaredField("modifiers");
                                        modifiers.setAccessible(true);
                                        modifiers.setInt(field, field.getModifiers() & ~Modifier.FINAL);

                                        if (field.getGenericType() instanceof ParameterizedType) {
                                            Type[] types = ((ParameterizedType) field.getGenericType())
                                                    .getActualTypeArguments();
                                            Class[] clas = new Class[] {};
                                            for (Type type : types) {
                                                if (type instanceof Class) {
                                                    clas = ArrayUtils.add(clas, (Class) type);
                                                }
                                            }
                                            field.set(o, mbt.fromNBT(nbt.getTag(field.getName()),
                                                    field.getType(), clas));
                                        } else {
                                            field.set(o,
                                                    mbt.fromNBT(nbt.getTag(field.getName()), field.getType()));
                                        }
                                    }
                                } else {
                                    if (field.getGenericType() instanceof ParameterizedType) {
                                        Type[] types = ((ParameterizedType) field.getGenericType())
                                                .getActualTypeArguments();
                                        Class[] clas = new Class[] {};
                                        for (Type type : types) {
                                            if (type instanceof Class) {
                                                clas = ArrayUtils.add(clas, (Class) type);
                                            }
                                        }
                                        field.set(o, mbt.fromNBT(nbt.getTag(field.getName()), field.getType(),
                                                clas));
                                    } else {
                                        field.set(o, mbt.fromNBT(nbt.getTag(field.getName()), field.getType()));
                                    }
                                }
                            }
                        }
                    }
                }
            }
            clazz = encodeSuper ? clazz.getSuperclass() : Object.class;
        }
    } catch (IllegalArgumentException e) {
        Throwables.propagate(e);
    } catch (IllegalAccessException e) {
        Throwables.propagate(e);
    } catch (NoSuchFieldException e) {
        Throwables.propagate(e);
    } catch (SecurityException e) {
        Throwables.propagate(e);
    }
}

From source file:com.ngandroid.lib.NgAndroid.java

public <T> T buildScope(Class<T> clss) {
    T instance;// w ww. j a v  a 2s. c o  m
    try {
        instance = clss.newInstance();
        Field[] fields = clss.getDeclaredFields();
        for (Field f : fields) {
            f.setAccessible(true);
            Class type = f.getType();
            if (type.isInterface() && !f.isAnnotationPresent(Ignore.class)) {
                f.set(instance, buildModel(type));
            }
        }
    } catch (InstantiationException | IllegalAccessException e) {
        // TODO
        throw new RuntimeException("Error instantiating scope.", e);
    }
    return instance;
}

From source file:cz.zcu.kiv.eegdatabase.logic.indexing.PojoIndexer.java

/**
 * Finds a value of a field with the @SolrId annotation (if exists).
 * @param fields  Available class fields.
 * @param instance The class instance.//from w ww.j  a v a  2s  . c o m
 * @return The id value.
 */
private int getId(Field[] fields, Object instance) {
    for (Field field : fields) {
        if (field.isAnnotationPresent(SolrId.class)) {
            field.setAccessible(true); // necessary since the id field is private
            int id = 0;
            try {
                id = (Integer) field.get(instance);
            } catch (IllegalAccessException e) {
                log.error(e);
            } catch (IllegalArgumentException e) {
                log.error(e);
            }
            log.debug("ID: " + id);
            return id;
        }
    }
    // class doesn't contain the @SolrId annotation, throw an exception
    throw new RuntimeException("None of the fields contains the @SolrId annotation.");
}

From source file:de.liedtke.format.JSONFormatter.java

@Override
public <T extends BasicEntity> T reformat(final String object, final Class<T> entityClass)
        throws FormatException {
    T result = null;/*from  w  ww.  j av a  2 s  .  co m*/
    final Map<String, Field> fieldMap = new HashMap<String, Field>();
    if (entityClass.isAnnotationPresent(Entity.class)) {
        final Field[] fields = entityClass.getDeclaredFields();
        for (final Field field : fields) {
            if (field.isAnnotationPresent(FormatPart.class)) {
                fieldMap.put(field.getAnnotation(FormatPart.class).key(), field);
            }
        }
        try {
            final JSONObject json = new JSONObject(object);
            result = entityClass.newInstance();
            for (final String key : fieldMap.keySet()) {
                if (json.has(key)) {
                    final Field field = fieldMap.get(key);
                    final Method method = entityClass.getMethod(this.getSetter(field.getName()),
                            new Class<?>[] { field.getType() });
                    if (FindInterface.class.isAssignableFrom(field.getType())) {
                        final Method find = field.getType().getMethod("find", new Class<?>[] { String.class });
                        if (find != null) {
                            final Object enumObject = find.invoke(Enum.class, json.get(key));
                            method.invoke(result, enumObject);
                        }
                    } else {
                        final String type = field.getType().toString();
                        if (type.equals("class com.google.appengine.api.datastore.Key")) {
                            method.invoke(result, KeyFactory.stringToKey(json.getString(key)));
                        } else if (type.equals("class com.google.appengine.api.datastore.Text")) {
                            method.invoke(result, new Text(json.getString(key)));
                        } else if (type.equals("boolean")) {
                            method.invoke(result, json.getBoolean(key));
                        } else if (type.equals("long")) {
                            method.invoke(result, json.getLong(key));
                        } else if (type.equals("int")) {
                            method.invoke(result, json.getInt(key));
                        } else {
                            method.invoke(result, json.get(key));
                        }
                    }
                }
            }
        } catch (JSONException e) {
            logger.warning("JSONException occured: " + e.getMessage());
            throw new FormatException();
        } catch (NoSuchMethodException e) {
            logger.warning("NoSuchMethodException occured: " + e.getMessage());
            throw new FormatException();
        } catch (SecurityException e) {
            logger.warning("SecurityException occured: " + e.getMessage());
            throw new FormatException();
        } catch (IllegalAccessException e) {
            logger.warning("IllegalAccessException occured: " + e.getMessage());
            throw new FormatException();
        } catch (IllegalArgumentException e) {
            logger.warning("IllegalArgumentException occured: " + e.getMessage());
            throw new FormatException();
        } catch (InvocationTargetException e) {
            logger.warning("InvocationTargetException occured: " + e.getMessage());
            throw new FormatException();
        } catch (InstantiationException e) {
            logger.warning("InstantiationException occured: " + e.getMessage());
            throw new FormatException();
        }
    }
    return result;
}

From source file:cz.zcu.kiv.eegdatabase.logic.indexing.PojoIndexer.java

/**
 * Removes the indexed POJO values from the Solr index.
 * @param instance POJO whose document in the index should be removed.
 * @throws IOException/*from www . jav  a  2 s .  c  om*/
 * @throws SolrServerException
 */
public void unindex(Object instance) throws IOException, SolrServerException {

    Field[] fields = instance.getClass().getDeclaredFields();
    String className = instance.getClass().getName();
    int id = 0;

    for (Field field : fields) {
        if (field.isAnnotationPresent(SolrId.class)) {
            field.setAccessible(true); // necessary since the id field is private
            try {
                id = (Integer) field.get(instance);
            } catch (IllegalAccessException e) {
                log.error(e);
            }
        }
    }

    String uuid = className + id;
    solrServer.deleteById(uuid);
    solrServer.commit();
}

From source file:org.cricket.hawkeye.codegen.fetcher.AbstractFetcherMethodImpl.java

@Override
public boolean populate(SourceVO sourceVO) throws HawkEyeCodeTemplateException {
    FetcherTemplate fetcherTempl = this.getFetcherTemplate();

    Class clazz = sourceVO.getClass();
    int i = 0;//ww  w.ja va2  s . co  m
    for (Field declField : clazz.getDeclaredFields()) {

        if (declField.isAnnotationPresent(HQLGenerate.class)) {
            boolean isImplemented = this.fieldImplements(declField);
            if (isImplemented) {
                this.setFieldData(declField);
                i++;
            }
        }
    }
    fetcherTempl.setSize(String.valueOf(i));
    return true;
}

From source file:org.craftercms.commons.jackson.mvc.CrafterJackson2MessageConverter.java

private void runAnnotations(final Object object) {
    try {//from w w  w.j a  va  2 s  . c  om

        if (Iterable.class.isInstance(object) && !Iterator.class.isInstance(object)) {
            for (Object element : (Iterable) object) {
                runAnnotations(element);
            }
        }
        PropertyDescriptor[] propertiesDescriptor = PropertyUtils.getPropertyDescriptors(object);
        for (PropertyDescriptor propertyDescriptor : propertiesDescriptor) {
            // Avoid the "getClass" as a property
            if (propertyDescriptor.getPropertyType().equals(Class.class)
                    || (propertyDescriptor.getReadMethod() == null
                            && propertyDescriptor.getWriteMethod() == null)) {
                continue;
            }
            Field field = findField(object.getClass(), propertyDescriptor.getName());

            if (field != null && field.isAnnotationPresent(SecureProperty.class)
                    && securePropertyHandler != null) {
                secureProperty(object, field);
            }

            if (field != null && field.isAnnotationPresent(InjectValue.class) && injectValueFactory != null) {
                injectValue(object, field);
                continue;
            }

            Object fieldValue = PropertyUtils.getProperty(object, propertyDescriptor.getName());
            if (Iterable.class.isInstance(fieldValue) && !Iterator.class.isInstance(object)) {
                for (Object element : (Iterable) fieldValue) {
                    runAnnotations(element);
                }
            }
        }
    } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
        log.error("Unable to secure value for " + object.getClass(), e);
    }
}