Example usage for java.lang.reflect Field getAnnotation

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

Introduction

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

Prototype

public <T extends Annotation> T getAnnotation(Class<T> annotationClass) 

Source Link

Usage

From source file:bdi4jade.util.ReflectionUtils.java

/**
 * Sets plan body fields annotated with {@link bdi4jade.annotation.Belief}.
 * /*w ww .ja v  a  2  s .c om*/
 * @param planBody
 *            the plan body to be setup with beliefs.
 */
public static void setupBeliefs(PlanBody planBody) {
    Capability capability = planBody.getPlan().getPlanLibrary().getCapability();
    Class<?> currentClass = planBody.getClass();
    while (PlanBody.class.isAssignableFrom(currentClass)) {
        for (Field field : currentClass.getDeclaredFields()) {
            boolean b = field.isAccessible();
            field.setAccessible(true);
            try {
                if (field.isAnnotationPresent(bdi4jade.annotation.Belief.class)) {
                    if (Belief.class.isAssignableFrom(field.getType())) {
                        bdi4jade.annotation.Belief beliefAnnotation = field
                                .getAnnotation(bdi4jade.annotation.Belief.class);
                        String beliefName = beliefAnnotation.name();
                        if (beliefName == null || "".equals(beliefName)) {
                            beliefName = field.getName();
                        }
                        Belief<?, ?> belief = capability.getBeliefBase().getBelief(beliefName);
                        field.set(planBody, belief);
                    } else {
                        throw new ClassCastException("Field " + field.getName() + " should be a Belief");
                    }
                }
            } catch (Exception exc) {
                log.warn(exc);
            }
            field.setAccessible(b);
        }
        currentClass = currentClass.getSuperclass();
    }
}

From source file:com.google.code.simplestuff.bean.SimpleBean.java

/**
 * Compare two bean basing the comparison only on the {@link BusinessField}
 * annotated fields.//from   www  . java 2  s . c om
 * 
 * @param firstBean First bean to compare.
 * @param secondBean Second bean to compare.
 * @return The equals result.
 * @throws IllegalArgumentException If one of the beans compared is not an
 *         instance of a {@link BusinessObject} annotated class.
 */
public static boolean equals(Object firstBean, Object secondBean) {

    // null + !null = false
    // null + null = true
    if ((firstBean == null) || (secondBean == null)) {
        if ((firstBean == null) && (secondBean == null)) {
            return true;
        } else {
            return false;
        }
    }

    final BusinessObjectDescriptor firstBusinessObjectInfo = BusinessObjectContext
            .getBusinessObjectDescriptor(firstBean.getClass());
    final BusinessObjectDescriptor secondBusinessObjectInfo = BusinessObjectContext
            .getBusinessObjectDescriptor(secondBean.getClass());

    // We don't need here a not null check since by contract the
    // getBusinessObjectDescriptor method always returns an abject.

    // All this conditions are to support the case in which
    // SimpleBean.equals is used in not Business Object. Than the rules are:
    // !BO.equals(!BO) = The objects are equals if one of them is assignable
    // to the other (the or is used for the respect the symmetric rule)
    // !BO.eqauls(BO) = The equals of the !BO is used.
    // BO.equals(!BO) = The equals of the !BO is used.
    if (firstBusinessObjectInfo.getNearestBusinessObjectClass() == null) {
        if (secondBusinessObjectInfo.getNearestBusinessObjectClass() == null) {
            return firstBean.getClass().isAssignableFrom(secondBean.getClass())
                    || secondBean.getClass().isAssignableFrom(firstBean.getClass());
        } else {
            return firstBean.equals(secondBean);
        }
    } else if (secondBusinessObjectInfo.getNearestBusinessObjectClass() == null) {
        return secondBean.equals(firstBean);
    }

    // TODO: Revise this code in order to make it more readable...
    // If one of the two bean has the class with Business relevance then
    // we need to compare the lowest hierarchical annotated classes of
    // the two beans.
    if ((firstBusinessObjectInfo.isClassToBeConsideredInComparison()
            || secondBusinessObjectInfo.isClassToBeConsideredInComparison())
            && (!firstBusinessObjectInfo.getNearestBusinessObjectClass()
                    .equals(secondBusinessObjectInfo.getNearestBusinessObjectClass()))) {
        // If the comparison fails than we can already return false.
        return false;
    }

    // Then we continue with the annotated fields, first checking
    // if the two objects contain the same annotated fields. A paranoid
    // comparison (both sides) is done only if the two objects are not on
    // the same class in order to handle tricky cases.
    final boolean performParanoidComparison = false;
    if (!compareAnnotatedFieldsByName(firstBusinessObjectInfo.getAnnotatedFields(),
            secondBusinessObjectInfo.getAnnotatedFields(), performParanoidComparison)) {
        // If the comparison fails than we can already return false.
        return false;
    }

    // Then we continue with the values of the annotated fields.
    Collection<Field> firstBeanAnnotatedFields = firstBusinessObjectInfo.getAnnotatedFields();

    for (Field field : firstBeanAnnotatedFields) {

        final BusinessField fieldAnnotation = field.getAnnotation(BusinessField.class);
        // Since the cycle is on the annotated Field we are sure that
        // fieldAnnotation will always be not null.
        if (fieldAnnotation.includeInEquals()) {

            Object firstBeanFieldValue = null;
            Object secondBeanFieldValue = null;

            try {
                firstBeanFieldValue = PropertyUtils.getProperty(firstBean, field.getName());
                // Also in this case, since before of the cycle we
                // compare the annotated fields, we can be sure that the
                // field exists.
                secondBeanFieldValue = PropertyUtils.getProperty(secondBean, field.getName());

                // If there were problems (like when we compare
                // different Business Object with different Business
                // Fields), then we return false.
            } catch (IllegalAccessException e) {
                if (log.isDebugEnabled()) {
                    log.debug("IllegalAccessException exception when comparing class "
                            + firstBean.getClass().toString() + " with class"
                            + secondBean.getClass().toString(), e);
                }
                return false;
            } catch (InvocationTargetException e) {
                if (log.isDebugEnabled()) {
                    log.debug("InvocationTargetException exceptionwhen comparing class "
                            + firstBean.getClass().toString() + " with class"
                            + secondBean.getClass().toString(), e);
                }
                return false;
            } catch (NoSuchMethodException e) {
                if (log.isDebugEnabled()) {
                    log.debug("NoSuchMethodException exception when comparing class "
                            + firstBean.getClass().toString() + " with class"
                            + secondBean.getClass().toString(), e);
                }
                return false;
            }

            // Some date implementations give not exact
            // comparison...
            if ((ClassUtils.isAssignable(field.getType(), Date.class))
                    || (ClassUtils.isAssignable(field.getType(), Calendar.class))) {

                if (firstBeanFieldValue != null) {
                    firstBeanFieldValue = DateUtils.round(firstBeanFieldValue, Calendar.MILLISECOND);
                }

                if (secondBeanFieldValue != null) {
                    secondBeanFieldValue = DateUtils.round(secondBeanFieldValue, Calendar.MILLISECOND);
                }

            }

            // We use always EqualsBuilder since we can get also
            // primitive arrays and they need ot be internally
            // compared.
            EqualsBuilder equalsBuilder = new EqualsBuilder();
            equalsBuilder.append(firstBeanFieldValue, secondBeanFieldValue);
            if (!equalsBuilder.isEquals()) {
                return false;
            } else {

                // If we are here the bean are both not null and
                // equals or both null (then equals)... the cycle
                // can
                // continue...
                continue;
            }

        }
    }

    // If we finally arrive here, then all the comparison were
    // successful and the two beans are equals.
    return true;

}

From source file:cn.afterturn.easypoi.util.PoiPublicUtil.java

/**
 * //from   w w  w.  ja  v a  2s.  c o m
 *
 * @param clazz
 * @return
 */
public static Object createObject(Class<?> clazz, String targetId) {
    Object obj = null;
    try {
        if (clazz.equals(Map.class)) {
            return new LinkedHashMap<String, Object>();
        }
        obj = clazz.newInstance();
        Field[] fields = getClassFields(clazz);
        for (Field field : fields) {
            if (isNotUserExcelUserThis(null, field, targetId)) {
                continue;
            }
            if (isCollection(field.getType())) {
                ExcelCollection collection = field.getAnnotation(ExcelCollection.class);
                PoiReflectorUtil.fromCache(clazz).setValue(obj, field.getName(),
                        collection.type().newInstance());
            } else if (!isJavaClass(field) && !field.getType().isEnum()) {
                PoiReflectorUtil.fromCache(clazz).setValue(obj, field.getName(),
                        createObject(field.getType(), targetId));
            }
        }

    } catch (Exception e) {
        LOGGER.error(e.getMessage(), e);
        throw new RuntimeException("");
    }
    return obj;

}

From source file:org.uimafit.factory.ConfigurationParameterFactory.java

/**
 * Determines the default value of an annotated configuration parameter. The returned value is
 * not necessarily the value that the annotated member variable will be instantiated with in
 * ConfigurationParameterInitializer which does extra work to convert the UIMA configuration
 * parameter value to comply with the type of the member variable.
 */// w  w w  .j a v a 2 s  . c  o  m
public static Object getDefaultValue(Field field) {
    if (isConfigurationParameterField(field)) {
        org.uimafit.descriptor.ConfigurationParameter annotation = field
                .getAnnotation(org.uimafit.descriptor.ConfigurationParameter.class);

        String[] stringValue = annotation.defaultValue();
        if (stringValue.length == 1
                && stringValue[0].equals(org.uimafit.descriptor.ConfigurationParameter.NO_DEFAULT_VALUE)) {
            return null;
        }

        String valueType = getConfigurationParameterType(field);
        boolean isMultiValued = isMultiValued(field);

        if (!isMultiValued) {
            if (ConfigurationParameter.TYPE_BOOLEAN.equals(valueType)) {
                return Boolean.parseBoolean(stringValue[0]);
            } else if (ConfigurationParameter.TYPE_FLOAT.equals(valueType)) {
                return Float.parseFloat(stringValue[0]);
            } else if (ConfigurationParameter.TYPE_INTEGER.equals(valueType)) {
                return Integer.parseInt(stringValue[0]);
            } else if (ConfigurationParameter.TYPE_STRING.equals(valueType)) {
                return stringValue[0];
            }
            throw new UIMA_IllegalArgumentException(
                    UIMA_IllegalArgumentException.METADATA_ATTRIBUTE_TYPE_MISMATCH,
                    new Object[] { valueType, "type" });
        } else {
            if (ConfigurationParameter.TYPE_BOOLEAN.equals(valueType)) {
                Boolean[] returnValues = new Boolean[stringValue.length];
                for (int i = 0; i < stringValue.length; i++) {
                    returnValues[i] = Boolean.parseBoolean(stringValue[i]);
                }
                return returnValues;
            } else if (ConfigurationParameter.TYPE_FLOAT.equals(valueType)) {
                Float[] returnValues = new Float[stringValue.length];
                for (int i = 0; i < stringValue.length; i++) {
                    returnValues[i] = Float.parseFloat(stringValue[i]);
                }
                return returnValues;
            } else if (ConfigurationParameter.TYPE_INTEGER.equals(valueType)) {
                Integer[] returnValues = new Integer[stringValue.length];
                for (int i = 0; i < stringValue.length; i++) {
                    returnValues[i] = Integer.parseInt(stringValue[i]);
                }
                return returnValues;
            } else if (ConfigurationParameter.TYPE_STRING.equals(valueType)) {
                return stringValue;
            }
            throw new UIMA_IllegalArgumentException(
                    UIMA_IllegalArgumentException.METADATA_ATTRIBUTE_TYPE_MISMATCH,
                    new Object[] { valueType, "type" });

        }

    } else {
        throw new IllegalArgumentException("field is not annotated with annotation of type "
                + org.uimafit.descriptor.ConfigurationParameter.class.getName());
    }
}

From source file:com.plusub.lib.annotate.JsonParserUtils.java

/**
 * ?JSONobjEntity//from  ww w . j  a va 2s.c o  m
 * <p>Title: initEntityParser
 * <p>Description: 
 * @param className ?
 * @param jsonString JSON
 * @param isParserList ?className?@JsonParserClass
 * @throws Exception
 */
public static Object initEntityParser(Class className, String jsonString, boolean isParserList)
        throws Exception {
    JSONObject jo = new JSONObject(jsonString);
    Object obj = getInstance(className.getName());

    JsonParserClass jsonClass = obj.getClass().getAnnotation(JsonParserClass.class);
    String rootKey = "";
    boolean isHasPage = false;
    String pageKey = "";
    if (jsonClass != null) {
        rootKey = jsonClass.parserRoot();
        isHasPage = jsonClass.isHasPage();
        pageKey = jsonClass.pageFieldStr();
    }
    Object result = null;

    if (!isParserList) {
        if (isEmpty(rootKey)) {
            result = parserField(obj, jo);
        } else {
            JSONObject json = JSONUtils.getJSONObject(jo, rootKey, null);
            if (json != null) {
                result = parserField(obj, json);
            }
        }
    } else {
        Object pageObj = null;
        //?page
        if (isHasPage) {
            Field field;
            try {
                field = obj.getClass().getDeclaredField(pageKey);
                JsonParserField jsonField = field.getAnnotation(JsonParserField.class);
                String key = jsonField.praserKey();
                if (isEmpty(key)) {
                    key = field.getName();
                }
                JSONObject pageJO = JSONUtils.getJSONObject(jo, key, null);
                if (pageJO != null) {
                    pageObj = getPageInfo(pageJO, field);
                    setFieldValue(obj, field, pageObj);
                }
            } catch (NoSuchFieldException e) {
                // TODO Auto-generated catch block
                if (showLog) {
                    Logger.e("JsonParserUtils", "Field" + pageKey);
                    e.printStackTrace();
                }
            }
        }

        //?
        JSONArray ja = JSONUtils.getJSONArray(jo, rootKey, null);
        if (ja != null && ja.length() > 0) {
            int size = ja.length();
            Object[] data = new Object[size];
            //?
            for (int index = 0; index < size; index++) {
                Object oj = parserField(getInstance(className.getName()), ja.getJSONObject(index));

                //page?
                if (isHasPage && pageObj != null) {
                    try {
                        setFieldValue(oj, oj.getClass().getDeclaredField(pageKey), pageObj);
                    } catch (NoSuchFieldException e) {
                        // TODO Auto-generated catch block
                        if (showLog) {
                            e.printStackTrace();
                        }
                    }
                }

                data[index] = oj;
            }
            result = Arrays.asList(data);
        } else {
            if (showLog) {
                Logger.i(TAG, "JSONArray is Empty " + rootKey);
            }
        }
    }

    return result;
}

From source file:com.zc.util.refelect.Reflector.java

/**
 * ?fieldannotationClass/*from   ww  w.  ja  v  a 2s . c  o m*/
 *
 * @param field
 *            field
 * @param annotationClass
 *            annotationClass
 *
 * @return {@link java.lang.annotation.Annotation}
 */
public static <T extends Annotation> T getAnnotation(Field field, Class annotationClass) {

    field.setAccessible(true);
    if (field.isAnnotationPresent(annotationClass)) {
        return (T) field.getAnnotation(annotationClass);
    }
    return null;
}

From source file:com.stratio.deep.cassandra.util.CassandraUtils.java

public static Cell createFromEntity(IDeepType e, Field field) {
    DeepField annotation = field.getAnnotation(DeepField.class);
    String cellName = deepFieldName(field);
    Object cellValue = getBeanFieldValue(e, field);
    boolean isClusterKey = annotation.isPartOfClusterKey();
    boolean isKey = annotation.isPartOfPartitionKey();
    return Cell.create(cellName, cellValue, isKey, isClusterKey);

}

From source file:net.ostis.sc.memory.SCKeynodesBase.java

protected static void init(SCSession session, Class<? extends SCKeynodesBase> klass) {
    if (log.isDebugEnabled())
        log.debug("Start retrieving keynodes for " + klass);

    try {/*from ww w  .ja  v  a2s  . c  o  m*/
        //
        // Search default segment for keynodes
        //
        SCSegment defaultSegment = null;
        {
            DefaultSegment annotation = klass.getAnnotation(DefaultSegment.class);
            if (annotation != null) {
                defaultSegment = session.openSegment(annotation.value());
                Validate.notNull(defaultSegment, "Default segment \"{0}\" not found", annotation.value());
                klass.getField(annotation.fieldName()).set(null, defaultSegment);
            }
        }

        Field[] fields = klass.getFields();
        for (Field field : fields) {
            int modifiers = field.getModifiers();

            if (Modifier.isPublic(modifiers) && Modifier.isStatic(modifiers)) {
                Class<?> type = field.getType();
                if (type.equals(SCSegment.class)) {
                    //
                    // We have segment field. Load segment by uri.
                    //
                    SegmentURI annotation = field.getAnnotation(SegmentURI.class);

                    if (annotation != null) {
                        String uri = annotation.value();
                        SCSegment segment = session.openSegment(uri);
                        field.set(null, segment);
                    } else {
                        // May be it already has value?
                        if (log.isWarnEnabled()) {
                            if (field.get(null) == null)
                                log.warn(field + " doesn't have value");
                        }
                    }
                } else {
                    if (!(checkKeynode(session, defaultSegment, field) || checkKeynodeURI(session, field)
                            || checkKeynodesNumberPatternURI(session, klass, field))) {

                        if (log.isWarnEnabled()) {
                            if (field.get(null) == null)
                                log.warn(field + " doesn't have annotations and value");
                        }

                    }
                }
            }
        }
    } catch (Exception e) {
        // TODO: handle
        e.printStackTrace();
    }
}

From source file:com.evolveum.midpoint.prism.marshaller.PrismBeanInspector.java

public static String findEnumFieldValueUncached(Class classType, String toStringValue) {
    for (Field field : classType.getDeclaredFields()) {
        XmlEnumValue xmlEnumValue = field.getAnnotation(XmlEnumValue.class);
        if (xmlEnumValue != null && field.getName().equals(toStringValue)) {
            return xmlEnumValue.value();
        }//w ww . ja v  a 2  s  .  com
    }
    return null;
}

From source file:com.github.maven_nar.NarUtil.java

/**
 * Produces a human-readable string of the given object which has fields
 * annotated with the Maven {@link Parameter} annotation.
 * //from  ww  w .  ja  v  a  2  s  .c o  m
 * @param o The object for which a human-readable string is desired.
 * @return A human-readable string, with each {@code @Parameter} field on a
 *         separate line rendered as a key/value pair.
 */
public static String prettyMavenString(final Object o) {
    final StringBuilder sb = new StringBuilder();
    sb.append(o.getClass().getName()).append(":\n");
    for (final Field f : o.getClass().getDeclaredFields()) {
        if (f.getAnnotation(Parameter.class) == null)
            continue;
        sb.append("\t").append(f.getName()).append("=").append(fieldValue(f, o)).append("\n");
    }
    return sb.toString();
}