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:org.b3log.latke.repository.jpa.EntityManagerImpl.java

/**
 * Converts the specified entity to a json object.
 * // w w  w  .j  a  v  a2 s  .  com
 * @param entity the specified entity
 * @return json object
 * @throws Exception exception
 */
private JSONObject toJSONObject(final Object entity) throws Exception {
    final JSONObject ret = new JSONObject();

    final Class<? extends Object> clazz = entity.getClass();
    final MetaEntity metaEntity = Entities.getMetaEntity(clazz);

    final Map<String, Field> fields = metaEntity.getFields();

    for (final Map.Entry<String, Field> entityField : fields.entrySet()) {
        final String fieldName = entityField.getKey();
        final Field field = entityField.getValue();
        final Class<?> fieldType = field.getType();

        field.setAccessible(true);
        final Object fieldValue = field.get(entity);

        if (field.isAnnotationPresent(Id.class)) {
            if (null != fieldValue) {
                ret.put(Keys.OBJECT_ID, fieldValue);
            }

            continue;
        }

        if (fieldType.isPrimitive() || String.class.equals(fieldType)) {
            ret.put(fieldName, fieldValue);
        }

        // TODO: relationships handling
    }

    return ret;
}

From source file:io.mandrel.common.schema.SchemaTest.java

public void inspect(int level, Type clazz, String name) {

    if (level > 6)
        return;//from w  w w . j ava2  s  .c o m
    if (clazz instanceof Class && clazz.equals(LinkFilter.class))
        return;

    if (clazz instanceof Class && !((Class<?>) clazz).isEnum() && ((Class<?>) clazz).getPackage() != null
            && ((Class<?>) clazz).getPackage().getName().startsWith("io.mandrel")) {
        int newLevel = level + 1;

        List<Field> fields = new ArrayList<Field>();
        Class<?> i = ((Class<?>) clazz);
        while (i != null && i != Object.class) {
            fields.addAll(Arrays.asList(i.getDeclaredFields()));
            i = i.getSuperclass();
        }

        for (Field field : fields) {
            Class<?> fieldType = field.getType();
            String text;
            if (!field.isAnnotationPresent(JsonIgnore.class) && !Modifier.isStatic(field.getModifiers())) {
                if (List.class.equals(fieldType) || Map.class.equals(fieldType)) {
                    Type type = field.getGenericType();
                    if (type instanceof ParameterizedType) {
                        ParameterizedType pType = (ParameterizedType) type;
                        for (Type paramType : pType.getActualTypeArguments()) {
                            if (paramType instanceof Class
                                    && NamedDefinition.class.isAssignableFrom((Class) paramType)) {
                                text = field.getName() + "(container of " + paramType + " oneOf)";
                                System.err.println(
                                        StringUtils.leftPad(text, text.length() + newLevel * 5, "\t-   "));
                                Class<? extends NamedDefinition> nd = (Class<? extends NamedDefinition>) field
                                        .getType();
                                Map<String, ? extends NamedDefinition> map = NamedProviders.get(nd);
                                map.forEach((k, v) -> {
                                    String text2 = k;
                                    System.err.println(StringUtils.leftPad(text2, text2.length() + newLevel * 5,
                                            "\t-   "));
                                    inspect(newLevel, v.getClass(), field.getName());
                                });
                            } else if (paramType instanceof ParameterizedType && NamedDefinition.class
                                    .isAssignableFrom((Class) ((ParameterizedType) paramType).getRawType())) {
                                text = field.getName() + "(container of " + paramType + " oneOf2)";
                                System.err.println(
                                        StringUtils.leftPad(text, text.length() + newLevel * 5, "\t-   "));
                                Class<? extends NamedDefinition> nd = (Class<? extends NamedDefinition>) ((ParameterizedType) paramType)
                                        .getRawType();
                                Map<String, ? extends NamedDefinition> map = NamedProviders.get(nd);
                                map.forEach((k, v) -> {
                                    String text2 = k;
                                    System.err.println(StringUtils.leftPad(text2, text2.length() + newLevel * 5,
                                            "\t-   "));
                                    inspect(newLevel, v.getClass(), field.getName());
                                });
                            } else if (paramType instanceof WildcardType) {
                                for (Type wildType : ((WildcardType) paramType).getUpperBounds()) {
                                    if (wildType instanceof Class
                                            && NamedDefinition.class.isAssignableFrom((Class) wildType)) {
                                        text = field.getName() + "(container of " + wildType + " oneOf)";
                                        System.err.println(StringUtils.leftPad(text,
                                                text.length() + newLevel * 5, "\t-   "));
                                        Class<? extends NamedDefinition> nd = (Class<? extends NamedDefinition>) field
                                                .getType();
                                        Map<String, ? extends NamedDefinition> map = NamedProviders.get(nd);
                                        map.forEach((k, v) -> {
                                            String text2 = k;
                                            System.err.println(StringUtils.leftPad(text2,
                                                    text2.length() + newLevel * 5, "\t-   "));
                                            inspect(newLevel, v.getClass(), field.getName());
                                        });
                                    } else if (wildType instanceof ParameterizedType
                                            && NamedDefinition.class.isAssignableFrom(
                                                    (Class) ((ParameterizedType) wildType).getRawType())) {
                                        text = field.getName() + "(container of " + wildType + " oneOf2)";
                                        System.err.println(StringUtils.leftPad(text,
                                                text.length() + newLevel * 5, "\t-   "));
                                        Class<? extends NamedDefinition> nd = (Class<? extends NamedDefinition>) ((ParameterizedType) wildType)
                                                .getRawType();
                                        Map<String, ? extends NamedDefinition> map = NamedProviders.get(nd);
                                        map.forEach((k, v) -> {
                                            String text2 = k;
                                            System.err.println(StringUtils.leftPad(text2,
                                                    text2.length() + newLevel * 5, "\t-   "));
                                            inspect(newLevel, v.getClass(), field.getName());
                                        });
                                    }
                                }
                            } else {
                                text = field.getName() + "(container of " + paramType + ")";
                                System.err.println(
                                        StringUtils.leftPad(text, text.length() + newLevel * 5, "\t-   "));
                                inspect(newLevel, paramType, "");
                            }
                        }
                    }
                } else {
                    if (NamedDefinition.class.isAssignableFrom(field.getType())) {
                        text = field.getName() + " oneOf";
                        System.err.println(StringUtils.leftPad(text, text.length() + newLevel * 5, "\t-   "));
                        Class<? extends NamedDefinition> nd = (Class<? extends NamedDefinition>) field
                                .getType();
                        Map<String, ? extends NamedDefinition> map = NamedProviders.get(nd);
                        map.forEach((k, v) -> {
                            String text2 = k;
                            System.err.println(
                                    StringUtils.leftPad(text2, text2.length() + newLevel * 5, "\t-   "));
                            inspect(newLevel, v.getClass(), field.getName());
                        });
                    } else {
                        text = field.getName()
                                + (field.getType().isPrimitive() || field.getType().equals(String.class)
                                        || field.getType().equals(LocalDateTime.class)
                                                ? " (" + field.getType().getName() + ")"
                                                : "");
                        System.err.println(StringUtils.leftPad(text, text.length() + newLevel * 5, "\t-   "));
                        inspect(newLevel, fieldType, field.getName());
                    }
                }

                // JsonSubTypes subtype =
                // fieldType.getAnnotation(JsonSubTypes.class);
                // if (subtype != null) {
                // int subLevel = level + 2;
                // text = "subtypes:";
                // System.err.println(StringUtils.leftPad(text,
                // text.length() + subLevel * 5, "\t-   "));
                // for (JsonSubTypes.Type type : subtype.value()) {
                // text = "subtype:" + type.name();
                // System.err.println(StringUtils.leftPad(text,
                // text.length() + (subLevel + 1) * 5, "\t-   "));
                // inspect((subLevel + 1), type.value(), type.name());
                // }
                // }
            }
        }

        JsonSubTypes subtype = ((Class<?>) clazz).getAnnotation(JsonSubTypes.class);
        if (subtype != null) {
            int subLevel = level + 1;
            String text = "subtypes:";
            System.err.println(StringUtils.leftPad(text, text.length() + subLevel * 5, "\t-   "));
            for (JsonSubTypes.Type type : subtype.value()) {
                text = "subtype:" + type.name();
                System.err.println(StringUtils.leftPad(text, text.length() + (subLevel + 1) * 5, "\t-   "));
                inspect((subLevel + 1), type.value(), type.name());
            }
        }
    }
}

From source file:it.restrung.rest.marshalling.response.AbstractJSONResponse.java

/**
 * @see JSONResponse#fromJSON(org.json.JSONObject)
 *///from   w ww  . j  av  a2 s  .  com
@Override
@SuppressWarnings("unchecked")
public void fromJSON(JSONObject jsonObject) throws JSONException {
    this.delegate = jsonObject;
    Method[] methods = getClass().getDeclaredMethods();
    for (Method method : methods) {
        if (method.getParameterTypes().length == 1 && method.getName().startsWith("set")
                && method.getName().length() > 3) {
            Class argType = method.getParameterTypes()[0];

            String propertyName = method.getName().substring(3);
            propertyName = propertyName.substring(0, 1).toLowerCase() + propertyName.substring(1);

            try {
                Field foundField = getClass().getDeclaredField(propertyName);
                if (foundField.isAnnotationPresent(JsonProperty.class)) {
                    propertyName = foundField.getAnnotation(JsonProperty.class).value();
                }
            } catch (NoSuchFieldException e) {
                //todo log errors when field names mismatch their setter
            }

            Object result = null;
            if (String.class.isAssignableFrom(argType)) {
                result = getString(propertyName);
            } else if (Boolean.class.isAssignableFrom(argType) || boolean.class.isAssignableFrom(argType)) {
                result = getBoolean(propertyName);
            } else if (Double.class.isAssignableFrom(argType) || double.class.isAssignableFrom(argType)) {
                result = getDouble(propertyName);
            } else if (Long.class.isAssignableFrom(argType) || long.class.isAssignableFrom(argType)) {
                result = getLong(propertyName);
            } else if (Integer.class.isAssignableFrom(argType) || int.class.isAssignableFrom(argType)) {
                result = getInt(propertyName);
            } else if (Date.class.isAssignableFrom(argType)) {
                result = getDate(propertyName);
            } else if (JSONResponse.class.isAssignableFrom(argType)) {
                result = getObject(propertyName, argType);
            } else if (Enum.class.isAssignableFrom(argType)) {
                String value = getString(propertyName);
                if (value != null) {
                    result = Enum.valueOf((Class<Enum>) argType, getString(propertyName));
                }
            } else if (List.class.isAssignableFrom(argType)) {
                Class typeArg = (Class) ((ParameterizedType) method.getGenericParameterTypes()[0])
                        .getActualTypeArguments()[0];
                if (JSONResponse.class.isAssignableFrom(typeArg)) {
                    result = getList(propertyName, typeArg);
                } else {
                    result = getElementCollection(propertyName);
                }
            } else if (Map.class.isAssignableFrom(argType)) {
                Class typeArg = (Class) ((ParameterizedType) method.getGenericParameterTypes()[0])
                        .getActualTypeArguments()[0];
                if (JSONResponse.class.isAssignableFrom(typeArg)) {
                    result = getMap(propertyName, typeArg);
                } else {
                    result = getElementMap(propertyName);
                }
            } else {
                throw new UnsupportedOperationException(String.format(
                        "%s is of type: %s which is not yet supported by the AbstractJSONResponse serialization",
                        propertyName, argType));
            }
            try {
                method.invoke(this, result);
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            } catch (InvocationTargetException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

From source file:com.basho.contact.actions.JSActionListener.java

private void wrapObjectWithAnnotations(Object o) {
    try {// ww w.  j  a  v a 2s. c  o m
        Context.enter();
        Field[] fields = o.getClass().getFields();
        for (Field f : fields) {
            if (f.isAnnotationPresent(Binding.class)) {
                Binding b = f.getAnnotation(Binding.class);
                String boundName = b.name();
                try {
                    //System.out.println("Binding " + boundName);
                    Object fieldValue = f.get(o);
                    Object wrappedObj = Context.javaToJS(fieldValue, jsscope);
                    ScriptableObject.putProperty(jsscope, boundName, wrappedObj);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    } finally {
        Context.exit();
    }
}

From source file:com.hazelcast.simulator.test.TestContainer.java

private Map<Field, Object> getInjectMap(Class classType) {
    Map<Field, Object> injectMap = new HashMap<Field, Object>();
    do {/*from w  ww.  j a  v a 2s  .  com*/
        for (Field field : classType.getDeclaredFields()) {
            Class fieldType = field.getType();
            if (field.isAnnotationPresent(InjectTestContext.class)) {
                assertFieldType(fieldType, TestContext.class, InjectTestContext.class);
                injectMap.put(field, testContext);
            } else if (field.isAnnotationPresent(InjectHazelcastInstance.class)) {
                assertFieldType(fieldType, HazelcastInstance.class, InjectHazelcastInstance.class);
                injectMap.put(field, testContext.getTargetInstance());
            } else if (field.isAnnotationPresent(InjectProbe.class)) {
                assertFieldType(fieldType, Probe.class, InjectProbe.class);
                String probeName = getProbeName(field);
                Probe probe = getOrCreateProbe(probeName, isThroughputProbe(field));
                injectMap.put(field, probe);
            }
        }
        classType = classType.getSuperclass();
    } while (classType != null);
    return injectMap;
}

From source file:de.ks.flatadocdb.metamodel.EntityDescriptor.java

public boolean isCollectionRelation(AnnotatedMember member) {
    if (member instanceof AnnotatedField) {
        Field field = ((AnnotatedField) member).getAnnotated();
        return field.isAnnotationPresent(Children.class) || field.isAnnotationPresent(ToMany.class);
    }/*from   w  w w . j a v  a2  s  .  c o  m*/
    return false;
}

From source file:de.ks.flatadocdb.metamodel.EntityDescriptor.java

public boolean isRelation(AnnotatedMember member) {
    if (member instanceof AnnotatedField) {
        Field field = ((AnnotatedField) member).getAnnotated();
        return field.isAnnotationPresent(Child.class) || field.isAnnotationPresent(Children.class)
                || field.isAnnotationPresent(ToOne.class) || field.isAnnotationPresent(ToMany.class);
    }/*  ww  w.  ja va2s  .co  m*/
    return false;
}

From source file:com.aw.core.db.support.WhereBuilder.java

public void buildColumn(Field field, Object columnValue) {
    String columnName = "";

    Method method = target.getPropertyDescriptor(field.getName()).getReadMethod();

    if (field.isAnnotationPresent(DAOSqlColumn.class)) {
        DAOSqlColumn column = field.getAnnotation(DAOSqlColumn.class);
        columnName = column.value();/*from  w  w w . j  ava2 s  .c o  m*/
    } else {
        if (dispatchAttribute.containsKey(field.getName())) {
            columnName = (String) dispatchAttribute.get(field.getName());
        } else {
            columnName = field.getName();
        }
    }
    boolean isLike = false;
    if (field.isAnnotationPresent(Like.class)) {
        columnValue = "%" + columnValue + "%";
        isLike = true;
    }
    boolean isUpper = false;
    if (field.isAnnotationPresent(Upper.class)) {
        //columnName = "upper("+columnName+")";
        isUpper = true;
    }
    columns.add(new Column(field.getName(), columnName, columnValue, isLike, isUpper));
}

From source file:de.extra.client.core.annotation.PropertyPlaceholderPluginConfigurer.java

private void setPluginProperties(final ConfigurableListableBeanFactory beanFactory, final Properties properties,
        final String beanName, final Class<?> clazz) {
    final PluginConfiguration annotationConfigutation = clazz.getAnnotation(PluginConfiguration.class);
    final MutablePropertyValues mutablePropertyValues = beanFactory.getBeanDefinition(beanName)
            .getPropertyValues();//from  ww w  .  j  av  a 2s  .  c om

    for (final PropertyDescriptor property : BeanUtils.getPropertyDescriptors(clazz)) {
        final Method setter = property.getWriteMethod();
        PluginValue valueAnnotation = null;
        if (setter != null && setter.isAnnotationPresent(PluginValue.class)) {
            valueAnnotation = setter.getAnnotation(PluginValue.class);
        }
        if (valueAnnotation != null) {
            final String key = extractKey(annotationConfigutation, valueAnnotation, clazz);
            final String value = resolvePlaceholder(key, properties, SYSTEM_PROPERTIES_MODE_FALLBACK);
            if (StringUtils.isEmpty(value)) {
                throw new BeanCreationException(beanName,
                        "No such property=[" + key + "] found in properties.");
            }
            if (LOG.isDebugEnabled()) {
                LOG.debug("setting property=[" + clazz.getName() + "." + property.getName() + "] value=[" + key
                        + "=" + value + "]");
            }
            mutablePropertyValues.addPropertyValue(property.getName(), value);
        }
    }

    for (final Field field : clazz.getDeclaredFields()) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("examining field=[" + clazz.getName() + "." + field.getName() + "]");
        }
        if (field.isAnnotationPresent(PluginValue.class)) {
            final PluginValue valueAnnotation = field.getAnnotation(PluginValue.class);
            final PropertyDescriptor property = BeanUtils.getPropertyDescriptor(clazz, field.getName());

            if (property == null || property.getWriteMethod() == null) {
                throw new BeanCreationException(beanName,
                        "setter for property=[" + clazz.getName() + "." + field.getName() + "] not available.");
            }
            final String key = extractKey(annotationConfigutation, valueAnnotation, clazz);
            String value = resolvePlaceholder(key, properties, SYSTEM_PROPERTIES_MODE_FALLBACK);
            if (value == null) {
                // DEFAULT Value suchen
                final int separatorIndex = key.indexOf(VALUE_SEPARATOR);
                if (separatorIndex != -1) {
                    final String actualPlaceholder = key.substring(0, separatorIndex);
                    final String defaultValue = key.substring(separatorIndex + VALUE_SEPARATOR.length());
                    value = resolvePlaceholder(actualPlaceholder, properties, SYSTEM_PROPERTIES_MODE_FALLBACK);
                    if (value == null) {
                        value = defaultValue;
                    }
                }
            }

            if (value != null) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("setting property=[" + clazz.getName() + "." + field.getName() + "] value=[" + key
                            + "=" + value + "]");
                }
                mutablePropertyValues.addPropertyValue(field.getName(), value);
            } else if (!ignoreNullValues) {
                throw new BeanCreationException(beanName,
                        "No such property=[" + key + "] found in properties.");
            }
        }
    }
}

From source file:io.github.benas.easyproperties.PropertyInjector.java

void injectProperty(final Field field, final Object object) throws PropertyInjectionException {
    //Introspect the field for each registered annotation, and delegate its processing to the corresponding annotation processor
    for (Class<? extends Annotation> annotationType : annotationProcessors.keySet()) {
        AnnotationProcessor annotationProcessor = annotationProcessors.get(annotationType);
        if (field.isAnnotationPresent(annotationType) && annotationProcessor != null) {
            Annotation annotation = field.getAnnotation(annotationType);
            doInjectProperty(field, object, annotation, annotationProcessor);
        }/* ww w  . j a  v  a2 s .co  m*/
    }
}