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.bitsofinfo.util.address.usps.ais.USPSUtils.java

/**
 * Given a Class and an List, this method will
 * populate the given List with all Field's for that Class and
 * all of its parent Classes in the inheritance tree
 * // w  ww .  j a v  a 2s.  co  m
 * @param fields
 * @param type the Class to check
 * @param stopAtClass, if the current class is equal to this, we go no further up the parent chains
 * @param   annotationClass the class of the annotation which must be present in 
 */
private void populateAllDeclaredFields(List<Field> fields, Class type, Class stopAtClass,
        Class<? extends Annotation> annotationClass) {
    for (Field field : type.getDeclaredFields()) {

        if (annotationClass != null) {
            if (field.isAnnotationPresent(annotationClass)) {
                fields.add(field);
            }
        } else {
            fields.add(field);
        }

        if (field.getType().isEnum()) {
            ConvertUtils.register(new GenericEnumConverter(), field.getType());
        }

    }

    // this is as far as we go...
    if (stopAtClass != null && stopAtClass == type) {
        return;
    }

    if (type.getSuperclass() != null) {
        populateAllDeclaredFields(fields, type.getSuperclass(), stopAtClass, annotationClass);
    }
}

From source file:org.openremote.server.inventory.DiscoveryService.java

protected Adapter createAdapter(String name, String componentType, UriEndpointComponent component,
        Properties componentProperties) {
    LOG.info("Creating adapter for component: " + name);
    Class<? extends Endpoint> endpointClass = component.getEndpointClass();

    String label = componentProperties.containsKey(COMPONENT_LABEL)
            ? componentProperties.get(COMPONENT_LABEL).toString()
            : null;//from www .  j a  va2 s  . c om

    if (label == null)
        throw new RuntimeException("Component missing label property: " + name);

    String discoveryEndpoint = componentProperties.containsKey(COMPONENT_DISCOVERY_ENDPOINT)
            ? componentProperties.get(COMPONENT_DISCOVERY_ENDPOINT).toString()
            : null;

    Adapter adapter = new Adapter(label, name, componentType, discoveryEndpoint);

    ComponentConfiguration config = component.createComponentConfiguration();
    ObjectNode properties = JSON.createObjectNode();
    for (Map.Entry<String, ParameterConfiguration> configEntry : config.getParameterConfigurationMap()
            .entrySet()) {
        try {
            Field field = endpointClass.getDeclaredField(configEntry.getKey());
            if (field.isAnnotationPresent(UriParam.class)) {
                UriParam uriParam = field.getAnnotation(UriParam.class);

                ObjectNode property = JSON.createObjectNode();

                if (uriParam.label().length() > 0) {
                    property.put("label", uriParam.label());
                }

                if (uriParam.description().length() > 0) {
                    property.put("description", uriParam.description());

                }

                if (uriParam.defaultValue().length() > 0) {
                    property.put("defaultValue", uriParam.defaultValue());
                }

                if (uriParam.defaultValueNote().length() > 0) {
                    property.put("defaultValueNote", uriParam.defaultValueNote());
                }

                if (String.class.isAssignableFrom(field.getType())) {
                    property.put("type", "string");
                } else if (Long.class.isAssignableFrom(field.getType())) {
                    property.put("type", "long");
                } else if (Integer.class.isAssignableFrom(field.getType())) {
                    property.put("type", "integer");
                } else if (Double.class.isAssignableFrom(field.getType())) {
                    property.put("type", "double");
                } else if (Boolean.class.isAssignableFrom(field.getType())) {
                    property.put("type", "boolean");
                } else {
                    throw new RuntimeException(
                            "Unsupported type of adapter endpoint property '" + name + "': " + field.getType());
                }

                if (field.isAnnotationPresent(NotNull.class)) {
                    for (Class<?> group : field.getAnnotation(NotNull.class).groups()) {
                        if (ValidationGroupDiscovery.class.isAssignableFrom(group)) {
                            property.put("required", true);
                            break;
                        }
                    }
                }

                String propertyName = uriParam.name().length() != 0 ? uriParam.name() : field.getName();
                LOG.debug("Adding adapter property '" + propertyName + "': " + property);
                properties.set(propertyName, property);
            }
        } catch (NoSuchFieldException ex) {
            // Ignoring config parameter if there is no annotated field on endpoint class
            // TODO: Inheritance of endpoint classes? Do we care?
        }
    }

    try {
        adapter.setProperties(JSON.writeValueAsString(properties));
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }

    return adapter;
}

From source file:org.apache.nifi.authorization.AuthorizerFactoryBean.java

private void performFieldInjection(final Authorizer instance, final Class authorizerClass)
        throws IllegalArgumentException, IllegalAccessException {
    for (final Field field : authorizerClass.getDeclaredFields()) {
        if (field.isAnnotationPresent(AuthorizerContext.class)) {
            // make the method accessible
            final boolean isAccessible = field.isAccessible();
            field.setAccessible(true);/*w w  w.j  ava 2 s.co m*/

            try {
                // get the type
                final Class<?> fieldType = field.getType();

                // only consider this field if it isn't set yet
                if (field.get(instance) == null) {
                    // look for well known types
                    if (NiFiProperties.class.isAssignableFrom(fieldType)) {
                        // nifi properties injection
                        field.set(instance, properties);
                    }
                }

            } finally {
                field.setAccessible(isAccessible);
            }
        }
    }

    final Class parentClass = authorizerClass.getSuperclass();
    if (parentClass != null && Authorizer.class.isAssignableFrom(parentClass)) {
        performFieldInjection(instance, parentClass);
    }
}

From source file:com.wit.android.support.fragment.manage.BaseFragmentFactory.java

/**
 * Processes all annotated fields marked with {@link com.wit.android.support.fragment.annotation.FactoryFragment @FactoryFragment}
 * annotation and puts them into the given <var>items</var> array.
 *
 * @param classOfFactory Class of this fragment factory.
 * @param items          Initial array of fragment items.
 *///from   w  w  w  .  j  a  v a  2 s .  co m
@SuppressWarnings("unchecked")
private void processAnnotatedFragments(final Class<?> classOfFactory, final SparseArray<FragmentItem> items) {
    FragmentAnnotations.iterateFields(classOfFactory, new FragmentAnnotations.FieldProcessor() {

        /**
         */
        @Override
        public void onProcessField(@NonNull Field field, @NonNull String name) {
            if (field.isAnnotationPresent(FactoryFragment.class) && int.class.equals(field.getType())) {
                final FactoryFragment factoryFragment = field.getAnnotation(FactoryFragment.class);
                try {
                    final int id = (int) field.get(BaseFragmentFactory.this);
                    items.put(id, new FragmentItem(id, TextUtils.isEmpty(factoryFragment.taggedName())
                            ? getFragmentTag(id)
                            : createFragmentTag(
                                    (Class<? extends FragmentController.FragmentFactory>) classOfFactory,
                                    factoryFragment.taggedName()),
                            factoryFragment.type()));
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
    });
}

From source file:com.gdcn.modules.db.jdbc.processor.CamelBeanProcessor.java

/**
 * Returns a PropertyDescriptor[] for the given Class.
 *
 * @param c The Class to retrieve PropertyDescriptors for.
 * @return A PropertyDescriptor[] describing the Class.
 * @throws SQLException if introspection failed.
 *//*ww w .  j a v  a  2  s  . c  o  m*/
private PropertyDescriptor[] propertyDescriptors(Class<?> c) throws SQLException {
    // Introspector caches BeanInfo classes for better performance
    BeanInfo beanInfo = null;
    try {
        beanInfo = Introspector.getBeanInfo(c);
    } catch (IntrospectionException e) {
        throw new SQLException("Bean introspection failed: " + e.getMessage());
    }
    List<PropertyDescriptor> propList = Lists.newArrayList();
    PropertyDescriptor[] props = beanInfo.getPropertyDescriptors();
    for (PropertyDescriptor prop : props) {
        String propName = prop.getName();
        try {
            Field field = ReflectionUtils.findField(c, propName);
            if (field != null && !field.isAnnotationPresent(Transient.class)) {//1.field=null 2.Transient??
                propList.add(prop);
            }
        } catch (SecurityException e) {
            throw new SQLException("Bean Get Field failed: " + e.getMessage());
        }
    }
    return propList.toArray(new PropertyDescriptor[propList.size()]);
}

From source file:org.mybatisorm.annotation.handler.TableHandler.java

public String getPrimaryKeyEqualFieldAnd() {
    StringBuilder sb = new StringBuilder();
    for (Field field : getPrimaryKeyFields()) {
        if (sb.length() > 0)
            sb.append(" AND ");
        if (field.isAnnotationPresent(TypeHandler.class)) {

        } else {/*from  ww  w .  ja  v a2  s .  co m*/
            // sb.append(ColumnAnnotation.getName(field)).append(" = #{").append(field.getName()).append("}");
            sb.append(TokenMaker.fieldEqual(field, null));
        }
    }
    return sb.toString();
}

From source file:com.impetus.kundera.metadata.processor.relation.ManyToOneRelationMetadataProcessor.java

@Override
public void addRelationIntoMetadata(Field relationField, EntityMetadata metadata) {
    // taking field's type as foreign entity, ignoring "targetEntity"
    Class<?> targetEntity = relationField.getType();

    ManyToOne ann = relationField.getAnnotation(ManyToOne.class);
    Relation relation = new Relation(relationField, targetEntity, null, ann.fetch(),
            Arrays.asList(ann.cascade()), ann.optional(), null, // mappedBy is null
            Relation.ForeignKey.MANY_TO_ONE);

    boolean isJoinedByFK = relationField.isAnnotationPresent(JoinColumn.class);

    if (relationField.isAnnotationPresent(AssociationOverride.class)) {
        AssociationOverride annotation = relationField.getAnnotation(AssociationOverride.class);
        JoinColumn[] joinColumns = annotation.joinColumns();

        relation.setJoinColumnName(joinColumns[0].name());

    } else if (isJoinedByFK) {
        JoinColumn joinColumnAnn = relationField.getAnnotation(JoinColumn.class);
        relation.setJoinColumnName(//from  ww w .j  ava 2s  . c  om
                StringUtils.isBlank(joinColumnAnn.name()) ? relationField.getName() : joinColumnAnn.name());
    } else {
        relation.setJoinColumnName(relationField.getName());
    }

    relation.setBiDirectionalField(metadata.getEntityClazz());
    metadata.addRelation(relationField.getName(), relation);

}

From source file:io.klerch.alexa.state.model.AlexaStateModel.java

/**
 * Checks, if the given field is tagged with AlexaStateSave
 * @param field the field you want to check for the AlexaStateSave-annotation
 * @return True, if the given field has the AlexaStateSave-annotation
 *//*from   ww  w .j a  v  a 2  s . c o m*/
private boolean isStateSave(final Field field) {
    // either field itself is annotated as statesave or whole class is
    // however, StateIgnore prevends field of being statesave
    return !field.isAnnotationPresent(AlexaStateIgnore.class)
            && (field.isAnnotationPresent(AlexaStateSave.class)
                    || this.getClass().isAnnotationPresent(AlexaStateSave.class));
}

From source file:com.jsmartframework.web.manager.BeanHelper.java

void setBeanFields(Class<?> clazz) {
    if (!beanFields.containsKey(clazz)) {

        List<Field> preSets = new ArrayList<>();
        List<Field> exposeVars = new ArrayList<>();

        for (Field field : getAllDeclaredFields(clazz)) {
            field.setAccessible(true);/*from  www. j a  va  2  s.  c  o  m*/
            if (field.isAnnotationPresent(PreSet.class)) {
                preSets.add(field);
            }

            if (field.isAnnotationPresent(ExposeVar.class)) {
                exposeVars.add(field);
                ExposeVar exposeVar = field.getAnnotation(ExposeVar.class);

                if (StringUtils.isNotBlank(exposeVar.value().i18n())) {
                    if (!field.getType().equals(Map.class)) {
                        throw new RuntimeException("Field [" + field + "] annotated with ExposeVar containing "
                                + "VarMapping attribute must be the type of Map<String, Object>");
                    }
                    setExposeVarMapping(field, exposeVar.value());
                }

                for (String varPath : cleanPaths(exposeVar.forPaths())) {
                    List<Class<?>> classes = exposeVarPaths.get(varPath);
                    if (classes == null) {
                        exposeVarPaths.put(varPath, classes = new ArrayList<>());
                    }
                    classes.add(clazz);
                }
            }
        }

        beanFields.put(clazz, getAllDeclaredFields(clazz));
        preSetFields.put(clazz, preSets.toArray(new Field[preSets.size()]));
        exposeVarFields.put(clazz, exposeVars.toArray(new Field[exposeVars.size()]));
    }
}

From source file:org.apache.nifi.authorization.AuthorityProviderFactoryBean.java

private void performFieldInjection(final AuthorityProvider instance, final Class authorityProviderClass)
        throws IllegalArgumentException, IllegalAccessException {
    for (final Field field : authorityProviderClass.getDeclaredFields()) {
        if (field.isAnnotationPresent(AuthorityProviderContext.class)) {
            // make the method accessible
            final boolean isAccessible = field.isAccessible();
            field.setAccessible(true);//from w w w.  j av  a2  s. c o  m

            try {
                // get the type
                final Class<?> fieldType = field.getType();

                // only consider this field if it isn't set yet
                if (field.get(instance) == null) {
                    // look for well known types
                    if (NiFiProperties.class.isAssignableFrom(fieldType)) {
                        // nifi properties injection
                        field.set(instance, properties);
                    } else if (ApplicationContext.class.isAssignableFrom(fieldType)) {
                        // spring application context injection
                        field.set(instance, applicationContext);
                    }
                }

            } finally {
                field.setAccessible(isAccessible);
            }
        }
    }

    final Class parentClass = authorityProviderClass.getSuperclass();
    if (parentClass != null && AuthorityProvider.class.isAssignableFrom(parentClass)) {
        performFieldInjection(instance, parentClass);
    }
}