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:com.google.code.simplestuff.bean.SimpleBean.java

/**
 * //  w ww .j  a v a  2  s.c  o  m
 * Returns the description of a bean considering only the
 * {@link BusinessField} annotated fields.
 * 
 * @param bean The bean to describe.
 * @return The description of the bean.
 * @throws IllegalArgumentException If the bean is not a Business Object.
 */
public static String toString(Object bean) {

    if (bean == null) {
        throw new IllegalArgumentException("The bean passed is null!!!");
    }

    BusinessObjectDescriptor businessObjectInfo = BusinessObjectContext
            .getBusinessObjectDescriptor(bean.getClass());

    if (businessObjectInfo == null) {
        return bean.toString();
        // throw new IllegalArgumentException(
        // "The bean passed is not annotated in the hierarchy as Business Object!!!");
    }

    Collection<Field> annotatedField = businessObjectInfo.getAnnotatedFields();
    ToStringBuilder builder = new ToStringBuilder(bean, ToStringStyle.MULTI_LINE_STYLE);
    for (Field field : annotatedField) {
        final BusinessField fieldAnnotation = field.getAnnotation(BusinessField.class);
        if ((fieldAnnotation != null) && (fieldAnnotation.includeInToString())) {
            try {
                // Vincenzo Vitale(vita) May 23, 2007 2:39:26 PM: some
                // date implementations give not equals values...
                if ((ClassUtils.isAssignable(field.getType(), Date.class))
                        || (ClassUtils.isAssignable(field.getType(), Calendar.class))) {
                    Object fieldValue = PropertyUtils.getProperty(bean, field.getName());
                    if (fieldValue != null) {
                        builder.append(DateUtils.round(fieldValue, Calendar.SECOND));
                    }

                } else {
                    builder.append(PropertyUtils.getProperty(bean, field.getName()));
                }
            } catch (IllegalAccessException e) {
                if (log.isDebugEnabled()) {
                    log.debug(
                            "IllegalAccessException exception when calculating the string representation of class"
                                    + bean.getClass().toString(),
                            e);
                }
            } catch (InvocationTargetException e) {
                if (log.isDebugEnabled()) {
                    log.debug(
                            "InvocationTargetException exception when calculating the string representation of class"
                                    + bean.getClass().toString(),
                            e);
                }
            } catch (NoSuchMethodException e) {
                if (log.isDebugEnabled()) {
                    log.debug(
                            "NoSuchMethodException exception when calculating the string representation of a bean of class"
                                    + bean.getClass().toString(),
                            e);
                }
            }
        }
    }

    return builder.toString();

}

From source file:com.github.fcannizzaro.resourcer.Resourcer.java

/**
 * Check the field annotation and execute its method
 *
 * @throws IllegalAccessException//from   ww w.j a v a  2  s  . c o m
 */
private static void switchAnnotation(Field field, Object annotated) throws IllegalAccessException {

    // File
    com.github.fcannizzaro.resourcer.annotations.Image image = field
            .getAnnotation(com.github.fcannizzaro.resourcer.annotations.Image.class);
    Audio audio = field.getAnnotation(Audio.class);
    Json json = field.getAnnotation(Json.class);

    // Values
    StringRes stringRes = field.getAnnotation(StringRes.class);
    IntegerRes integerRes = field.getAnnotation(IntegerRes.class);
    FloatRes floatRes = field.getAnnotation(FloatRes.class);
    DoubleRes doubleRes = field.getAnnotation(DoubleRes.class);
    LongRes longRes = field.getAnnotation(LongRes.class);
    BooleanRes booleanRes = field.getAnnotation(BooleanRes.class);
    ColorRes colorRes = field.getAnnotation(ColorRes.class);

    // grant access
    field.setAccessible(true);

    if (image != null) {
        annotateImage(field, image, annotated);
        return;
    }

    if (audio != null) {
        annotateAudio(field, audio, annotated);
        return;
    }

    if (json != null) {
        annotateJson(field, json, annotated);
        return;
    }

    if (stringRes != null && is(field, String.class)) {
        annotate(field, STRING, stringRes.value(), annotated);
        return;
    }

    if (integerRes != null) {
        annotate(field, INTEGER, integerRes.value(), annotated);
        return;
    }

    if (floatRes != null) {
        annotate(field, FLOAT, floatRes.value(), annotated);
        return;
    }

    if (doubleRes != null) {
        annotate(field, DOUBLE, doubleRes.value(), annotated);
        return;
    }

    if (longRes != null) {
        annotate(field, BOOLEAN, longRes.value(), annotated);
        return;
    }

    if (booleanRes != null) {
        annotate(field, BOOLEAN, booleanRes.value(), annotated);
        return;
    }

    if (colorRes != null && is(field, Color.class))
        annotate(field, COLOR, colorRes.value(), annotated);

}

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

/**
 * ??/*from  ww w . ja v  a  2  s.c om*/
 * <p>Title: parserField
 * <p>Description: 
 * @param obj
 * @param jsonObj
 * @return
 * @throws Exception
 */
private static Object parserField(Object obj, JSONObject jsonObj) throws Exception {
    Field[] fields = obj.getClass().getDeclaredFields();
    if (fields != null && fields.length > 0) {
        for (Field field : fields) {
            JsonParserField jsonField = field.getAnnotation(JsonParserField.class);

            //JsonParserField
            if (jsonField != null) {
                String keyName = jsonField.praserKey(); //json
                String defaultValue = jsonField.defaultValue(); //
                boolean isList = jsonField.isList();

                //???
                String name = "";
                if (isEmpty(keyName)) {
                    name = field.getName();
                } else {
                    name = keyName;
                }

                try {
                    field.setAccessible(true);
                    //?
                    if (jsonObj.has(name)) {
                        if (!isList) { //?
                            setSingleValue(obj, field, jsonObj, name);
                        } else { //
                            Class listCls = jsonField.classType();
                            if (listCls.equals(Object.class)) {
                                if (showLog)
                                    Logger.e(TAG, "" + field.getName()
                                            + "classType?" + keyName);
                            }
                            JSONArray ja = null;
                            if (isEmpty(keyName)) {
                                ja = JSONUtils.getJSONArray(jsonObj, field.getName(), null);
                            } else {
                                ja = JSONUtils.getJSONArray(jsonObj, keyName, null);
                            }
                            if (ja != null) {
                                //
                                int size = ja.length();
                                Object[] data = new Object[size];

                                //?
                                for (int index = 0; index < size; index++) {
                                    Object oj = parserField(getInstance(listCls.getName()),
                                            ja.getJSONObject(index));
                                    data[index] = oj;
                                }

                                //?
                                Object listObj = field.getType();
                                if (listObj.equals(List.class)) {
                                    setFieldValue(obj, field, Arrays.asList(data));
                                } else {
                                    setFieldValue(obj, field, data);
                                }
                            }
                        }
                    } else {
                        setFieldValue(obj, field, defaultValue);
                    }
                } catch (Exception e) {
                    throw new RuntimeException(
                            "parser " + obj.getClass().getName() + " error! \n" + e.getMessage());
                }
            } else { //JsonParserField
                setSingleValue(obj, field, jsonObj, field.getName());
            }
        }
    }
    return obj;
}

From source file:at.ac.tuwien.infosys.jcloudscale.utility.ReflectionUtil.java

public static void injectClientCloudObject(Object obj, ClientCloudObject cco) {

    for (Field f : obj.getClass().getFields()) {
        if (f.getAnnotation(ClientObject.class) != null) {

            f.setAccessible(true);//from  w w  w.j a v a 2 s .  c o  m
            try {
                f.set(obj, cco);
            } catch (Exception e) {
                e.printStackTrace();
                throw new JCloudScaleException(e, "Unexpected error when injecting @ClientCloudObject");
            }

        }
    }

}

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

/**
 * /*from  ww  w  .java 2 s.co m*/
 * Returns a test object with all the {@link BusinessField} annotated fields
 * set to a test value. TODO At the moment only the String field are
 * considered and the collection are not considered.
 * 
 * @param bean The class of the bean to fill.
 * @param suffix The suffix to append in the string field.
 * @return The bean with test values.
 */
public static <T> T getTestBean(Class<T> beanClass, String suffix) {
    if (beanClass == null) {
        throw new IllegalArgumentException("The bean class passed is null!!!");
    }

    T testBean = null;
    try {
        testBean = beanClass.newInstance();
    } catch (InstantiationException e1) {
        if (log.isDebugEnabled()) {
            log.debug(e1.getMessage());
        }
    } catch (IllegalAccessException e1) {
        if (log.isDebugEnabled()) {
            log.debug(e1.getMessage());
        }
    }

    BusinessObjectDescriptor businessObjectInfo = BusinessObjectContext.getBusinessObjectDescriptor(beanClass);

    // We don't need here a not null check since by contract the
    // getBusinessObjectDescriptor method always returns an abject.
    if (businessObjectInfo.getNearestBusinessObjectClass() != null) {

        Collection<Field> annotatedField = businessObjectInfo.getAnnotatedFields();
        for (Field field : annotatedField) {
            final BusinessField fieldAnnotation = field.getAnnotation(BusinessField.class);
            if (fieldAnnotation != null) {
                try {
                    if (field.getType().equals(String.class)) {
                        String stringValue = "test" + StringUtils.capitalize(field.getName())
                                + (suffix == null ? "" : suffix);
                        PropertyUtils.setProperty(testBean, field.getName(), stringValue);

                    } else if ((field.getType().equals(boolean.class))
                            || (field.getType().equals(Boolean.class))) {
                        PropertyUtils.setProperty(testBean, field.getName(), true);
                    } else if ((field.getType().equals(int.class)) || (field.getType().equals(Integer.class))) {
                        PropertyUtils.setProperty(testBean, field.getName(), 10);
                    } else if ((field.getType().equals(char.class))
                            || (field.getType().equals(Character.class))) {
                        PropertyUtils.setProperty(testBean, field.getName(), 't');
                    } else if ((field.getType().equals(long.class)) || (field.getType().equals(Long.class))) {
                        PropertyUtils.setProperty(testBean, field.getName(), 10L);
                    } else if ((field.getType().equals(float.class)) || (field.getType().equals(Float.class))) {
                        PropertyUtils.setProperty(testBean, field.getName(), 10F);
                    } else if ((field.getType().equals(byte.class)) || (field.getType().equals(Byte.class))) {
                        PropertyUtils.setProperty(testBean, field.getName(), (byte) 10);
                    } else if (field.getType().equals(Date.class)) {
                        PropertyUtils.setProperty(testBean, field.getName(), new Date());
                    } else if (field.getType().equals(Collection.class)) {
                        // TODO: create a test object of the collection
                        // class specified (if one is specified and
                        // recursively call this method.
                    }

                } catch (IllegalAccessException e) {
                    if (log.isDebugEnabled()) {
                        log.debug(e.getMessage());
                    }
                } catch (InvocationTargetException e) {
                    if (log.isDebugEnabled()) {
                        log.debug(e.getMessage());
                    }
                } catch (NoSuchMethodException e) {
                    if (log.isDebugEnabled()) {
                        log.debug(e.getMessage());
                    }
                }
            }
        }
    }

    return testBean;
}

From source file:at.ac.tuwien.infosys.jcloudscale.utility.ReflectionUtil.java

public static void checkLegalCloudIdDef(Object obj) {

    for (Field f : obj.getClass().getDeclaredFields()) {
        if (f.getAnnotation(CloudObjectId.class) != null) {

            if (!f.getType().equals(UUID.class) && !f.getType().equals(String.class)
                    && !f.getType().equals(Object.class))
                throw new IllegalDefinitionException("Illegal field type " + f.getType().getName()
                        + " annotated with "
                        + "@CloudObjectId. You may only annotate java.lang.Object, java.lang.String and java.util.UUID");

            if (Modifier.isStatic(f.getModifiers()))
                throw new IllegalDefinitionException("Illegal field " + f.getName()
                        + " annotated with @CloudObjectId. " + "Field has to be non-static.");

        }//ww w.j  av  a 2 s . c o m
    }

}

From source file:at.ac.tuwien.infosys.jcloudscale.utility.ReflectionUtil.java

public static void injectCloudId(Object obj, UUID id) {

    for (Field f : obj.getClass().getDeclaredFields()) {
        if (f.getAnnotation(CloudObjectId.class) != null) {

            f.setAccessible(true);//from w ww . j  a va2  s .  co m
            try {
                if (f.getType().equals(String.class))
                    f.set(obj, id.toString());
                else
                    f.set(obj, id);
            } catch (Exception e) {
                e.printStackTrace();
                throw new JCloudScaleException(e, "Unexpected error when injecting @CloudObjectId");
            }

        }
    }

}

From source file:at.ac.tuwien.infosys.jcloudscale.utility.ReflectionUtil.java

public static void injectEventSink(Object obj) {

    for (Field f : obj.getClass().getDeclaredFields()) {
        if (f.getAnnotation(EventSink.class) != null) {

            f.setAccessible(true);//from ww w  .j  a v  a 2  s . c  o m
            if (IEventSink.class.isAssignableFrom(f.getType()))
                try {
                    f.set(obj, new DefaultEventSink());
                } catch (Exception e) {
                    throw new JCloudScaleException(e, "Unexpected error when injecting into @EventSink");
                }
            else
                throw new JCloudScaleException("Cannot inject event sink into field " + f.getName() + ". "
                        + "Type needs to be IEventSink, but is " + f.getType().getCanonicalName());

        }
    }

}

From source file:io.github.moosbusch.lumpi.util.LumpiUtil.java

public static Map<String, Object> getBXMLFieldValues(Bindable obj) throws IllegalAccessException {
    Map<String, Object> result = new HashMap<>();
    Class<?> type = obj.getClass();
    Field[] allFields = FieldUtils.getAllFields(type);

    if (ArrayUtils.isNotEmpty(allFields)) {
        for (Field field : allFields) {
            BXML bxmlAnnotation = field.getAnnotation(BXML.class);

            if (bxmlAnnotation != null) {
                String id = bxmlAnnotation.id();
                Object fieldValue = FieldUtils.readField(field, obj, true);

                if (StringUtils.isNotBlank(id)) {
                    result.put(id, fieldValue);
                } else {
                    result.put(field.getName(), fieldValue);
                }//w ww  . j  av  a 2 s  .c  o m
            }
        }
    }

    return result;
}

From source file:at.ac.tuwien.infosys.jcloudscale.utility.ReflectionUtil.java

public static void checkLegalCloudInvocationInfoDef(Object obj) {

    for (Field f : obj.getClass().getDeclaredFields()) {
        if (f.getAnnotation(CloudInvocationInfos.class) != null) {

            Type[] genericTypes = ((ParameterizedType) f.getGenericType()).getActualTypeArguments();
            Class<?> typeParameter = (Class<?>) genericTypes[0];

            if (!f.getType().equals(List.class) || genericTypes.length != 1
                    || !typeParameter.equals(InvocationInfo.class))
                throw new IllegalDefinitionException("Illegal field type " + f.getType().getName()
                        + " annotated with "
                        + "@CloudInvocationInfos. You may only annotate java.util.List<InvocationInfo> fields.");

            if (Modifier.isStatic(f.getModifiers()))
                throw new IllegalDefinitionException("Illegal field " + f.getName()
                        + " annotated with @CloudInvocationInfos. " + "Field has to be non-static.");

        }//from ww w . j a v  a  2  s.  c  om
    }

}