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:bdi4jade.core.Capability.java

/**
 * Adds by reflection capability components, such as beliefs and plans,
 * according to annotated fields. This method is invoked by for capability
 * class, and all parent classes./* ww  w . j av a 2s. co  m*/
 * 
 * @param capabilityClass
 *            the capability class of which fields should me added to this
 *            capability.
 */
protected void addAnnotatedFields(Class<? extends Capability> capabilityClass) {
    for (Field field : capabilityClass.getDeclaredFields()) {
        boolean b = field.isAccessible();
        field.setAccessible(true);
        try {
            if (field.isAnnotationPresent(bdi4jade.annotation.Belief.class)) {
                if (Belief.class.isAssignableFrom(field.getType())) {
                    Belief<?, ?> belief = (Belief<?, ?>) field.get(this);
                    this.getBeliefBase().addBelief(belief);
                } else {
                    throw new ClassCastException("Field " + field.getName() + " should be a Belief");
                }
            } else if (field.isAnnotationPresent(bdi4jade.annotation.TransientBelief.class)) {
                bdi4jade.annotation.TransientBelief annotation = field
                        .getAnnotation(bdi4jade.annotation.TransientBelief.class);
                String name = "".equals(annotation.name()) ? field.getName() : annotation.name();
                Object value = field.get(this);
                this.getBeliefBase().addBelief(new TransientBelief(name, value));
            } else if (field.isAnnotationPresent(bdi4jade.annotation.TransientBeliefSet.class)) {
                bdi4jade.annotation.TransientBeliefSet annotation = field
                        .getAnnotation(bdi4jade.annotation.TransientBeliefSet.class);
                String name = "".equals(annotation.name()) ? field.getName() : annotation.name();
                Object value = field.get(this);
                if (Set.class.isAssignableFrom(field.getType())) {
                    this.getBeliefBase().addBelief(new TransientBeliefSet(name, (Set) value));
                }
            } else if (field.isAnnotationPresent(bdi4jade.annotation.Plan.class)) {
                if (Plan.class.isAssignableFrom(field.getType())) {
                    Plan plan = (Plan) field.get(this);
                    this.getPlanLibrary().addPlan(plan);
                } else {
                    throw new ClassCastException("Field " + field.getName() + " should be a Plan");
                }
            } else if (field.isAnnotationPresent(bdi4jade.annotation.AssociatedCapability.class)) {
                if (Capability.class.isAssignableFrom(field.getType())) {
                    Capability capability = (Capability) field.get(this);
                    this.addAssociatedCapability(capability);
                } else {
                    throw new ClassCastException("Field " + field.getName() + " should be a Capability");
                }
            } else if (field.isAnnotationPresent(bdi4jade.annotation.PartCapability.class)) {
                if (Capability.class.isAssignableFrom(field.getType())) {
                    Capability capability = (Capability) field.get(this);
                    this.addPartCapability(capability);
                } else {
                    throw new ClassCastException("Field " + field.getName() + " should be a Capability");
                }
            }
        } catch (Exception exc) {
            log.warn(exc);
            exc.printStackTrace();
        }
        field.setAccessible(b);
    }
}

From source file:net.eledge.android.toolkit.db.internal.TableBuilder.java

private String createFieldDef(Class<?> clazz, Field field) {
    FieldType type = FieldType.getType(field.getType());
    Column column = field.getAnnotation(Column.class);
    if (StringUtils.isNotEmpty(column.columnDefinition())) {
        return column.columnDefinition();
    }//from w w w  . j av  a2 s .  c  om
    StringBuilder sb = new StringBuilder();
    sb.append(SQLBuilder.getFieldName(field, column));
    sb.append(" ").append(type.columnType);
    if (column.unique()) {
        sb.append(" UNIQUE");
    }
    try {
        if (!column.nullable()) {
            sb.append(" NOT NULL");
            sb.append(" DEFAULT ").append(type.defaultValue(clazz.newInstance(), field));
        }
    } catch (Exception e) {
        Log.e(this.getClass().getName(), e.getMessage(), e);
    }
    if (field.isAnnotationPresent(Id.class)) {
        sb.append(" PRIMARY KEY");
    }
    return sb.toString();
}

From source file:hd3gtv.mydmam.db.orm.CassandraOrm.java

private void createColumnFamily() throws IOException, ConnectionException {

    CassandraDb.createColumnFamilyString(CassandraDb.getDefaultKeyspacename(), columnfamily.getName(),
            createOrmObject().hasLongGracePeriod());

    ArrayList<Field> fields = getOrmobjectUsableFields();
    Field field;
    String colstype;//w w w  . jav  a 2s .  com
    Class<?> fieldtype;
    for (int pos_df = 0; pos_df < fields.size(); pos_df++) {
        field = fields.get(pos_df);
        if (field.isAnnotationPresent(CassandraIndexed.class) == false) {
            continue;
        }
        fieldtype = field.getType();
        if (fieldtype.isAssignableFrom(String.class)) {
            colstype = DeployColumnDef.ColType_UTF8Type;
        } else if (fieldtype.isAssignableFrom(Byte[].class) | fieldtype.isAssignableFrom(byte.class)) {
            colstype = DeployColumnDef.ColType_BytesType;
        } else if (fieldtype.isAssignableFrom(Integer.class) | fieldtype.isAssignableFrom(int.class)) {
            colstype = DeployColumnDef.ColType_IntegerType;
        } else if (fieldtype.isAssignableFrom(Long.class) | fieldtype.isAssignableFrom(long.class)) {
            colstype = DeployColumnDef.ColType_LongType;
        } else if (fieldtype.isAssignableFrom(Boolean.class) | fieldtype.isAssignableFrom(boolean.class)) {
            colstype = DeployColumnDef.ColType_IntegerType;
        } else if (fieldtype.isAssignableFrom(Date.class)) {
            colstype = DeployColumnDef.ColType_LongType;
        } else if (fieldtype.isAssignableFrom(Float.class) | fieldtype.isAssignableFrom(float.class)) {
            colstype = DeployColumnDef.ColType_AsciiType;
        } else if (fieldtype.isAssignableFrom(Double.class) | fieldtype.isAssignableFrom(double.class)) {
            colstype = DeployColumnDef.ColType_AsciiType;
        } else if (fieldtype.isAssignableFrom(UUID.class)) {
            colstype = DeployColumnDef.ColType_LexicalUUIDType;
        } else if (fieldtype.isAssignableFrom(JSONObject.class)) {
            colstype = DeployColumnDef.ColType_UTF8Type;
        } else if (fieldtype.isAssignableFrom(JSONArray.class)) {
            colstype = DeployColumnDef.ColType_UTF8Type;
        } else if (fieldtype.isAssignableFrom(InetAddress.class)) {
            colstype = DeployColumnDef.ColType_AsciiType;
        } else if (fieldtype.isAssignableFrom(StringBuffer.class)) {
            colstype = DeployColumnDef.ColType_UTF8Type;
        } else if (fieldtype.isAssignableFrom(Calendar.class)) {
            colstype = DeployColumnDef.ColType_LongType;
        } else if (fieldtype.isAssignableFrom(String[].class)) {
            colstype = DeployColumnDef.ColType_UTF8Type;
        } else {
            colstype = DeployColumnDef.ColType_BytesType;
        }

        CassandraDb.declareIndexedColumn(CassandraDb.getkeyspace(), columnfamily, field.getName(),
                getIndexName(field.getName()), colstype);
    }
}

From source file:org.broadinstitute.gatk.utils.commandline.ParsingEngine.java

/**
 * Gets a collection of the container instances of the given type stored within the given target.
 * @param source Argument source.//from  w w  w  .ja  v  a2 s.c  o m
 * @param instance Container.
 * @return A collection of containers matching the given argument source.
 */
private Collection<Object> findTargets(ArgumentSource source, Object instance) {
    LinkedHashSet<Object> targets = new LinkedHashSet<Object>();
    for (Class clazz = instance.getClass(); clazz != null; clazz = clazz.getSuperclass()) {
        for (Field field : clazz.getDeclaredFields()) {
            if (field.equals(source.field)) {
                targets.add(instance);
            } else if (field.isAnnotationPresent(ArgumentCollection.class)) {
                targets.addAll(findTargets(source, JVMUtils.getFieldValue(field, instance)));
            }
        }
    }
    return targets;
}

From source file:com.impetus.kundera.metadata.processor.TableProcessor.java

/**
 * Populate element collection into metadata.
 * //ww  w .j  a v  a2s .  c om
 * @param metadata
 *            the metadata
 * @param embeddedField
 *            the embedded field
 * @param embeddedFieldClass
 *            the embedded field class
 */
private void populateElementCollectionIntoMetadata(EntityMetadata metadata, Field embeddedField,
        Class embeddedFieldClass) {
    // If not annotated with @Embeddable, discard.
    Annotation ann = embeddedFieldClass.getAnnotation(Embeddable.class);
    if (ann == null) {
        LOG.warn(embeddedField.getName()
                + " was declared @ElementCollection but wasn't annotated with @Embeddable. "
                + " It won't be persisted co-located.");
        // return;
    }

    String embeddedFieldName = null;

    // Embedded object name should be the one provided with @CollectionTable
    // annotation, if not, should be
    // equal to field name
    if (embeddedField.isAnnotationPresent(CollectionTable.class)) {
        CollectionTable ct = embeddedField.getAnnotation(CollectionTable.class);
        if (!ct.name().isEmpty()) {
            embeddedFieldName = ct.name();
        } else {
            embeddedFieldName = embeddedField.getName();
        }
    } else {
        embeddedFieldName = embeddedField.getName();
    }

    addEmbeddedColumnInMetadata(metadata, embeddedField, embeddedFieldClass, embeddedFieldName);
}

From source file:org.broadinstitute.gatk.utils.help.GenericDocumentationHandler.java

/**
 * Utility function that finds the value of fieldName in any fields of ArgumentCollection fields in
 * instance of class c.//from  w  w  w.  j  a  v a  2  s.  c o m
 *
 * @param instance  the object to query for the field value
 * @param fieldName the name of the field we are looking for in instance
 * @return The value assigned to field in the ArgumentCollection, otherwise null
 */
private Object getFieldValue(Object instance, String fieldName) {
    //
    // subtle note.  If you have a field named X that is an ArgumentCollection that
    // contains a field X as well, you need only consider fields in the argumentCollection, not
    // matching the argument itself.
    //
    // @ArgumentCollection
    // protected DbsnpArgumentCollection dbsnp = new DbsnpArgumentCollection();
    //

    for (Field field : JVMUtils.getAllFields(instance.getClass())) {
        if (field.isAnnotationPresent(ArgumentCollection.class)) {
            //System.out.printf("Searching for %s in argument collection field %s%n", fieldName, field);
            Object fieldValue = JVMUtils.getFieldValue(field, instance);
            Object value = getFieldValue(fieldValue, fieldName);
            if (value != null)
                return value;
        } else if (field.getName().equals(fieldName)) {
            return JVMUtils.getFieldValue(field, instance);
        }
    }

    return null;
}

From source file:com.sxj.mybatis.orm.builder.GenericStatementBuilder.java

public GenericStatementBuilder(Configuration configuration, final Class<?> entityClass) {
    super(configuration);
    this.entityClass = entityClass;
    sharded = ConfigurationProperties.isSharded(configuration);
    String resource = entityClass.getName().replace('.', '/') + ".java (best guess)";
    assistant = new MapperBuilderAssistant(configuration, resource);
    entity = entityClass.getAnnotation(Entity.class);
    mapperType = entity.mapper();//from  w ww .  ja  v a2 s . c o  m

    if (!mapperType.isAssignableFrom(Void.class)) {
        namespace = mapperType.getName();
    } else {
        namespace = entityClass.getName();
    }
    assistant.setCurrentNamespace(namespace);
    Collection<String> cacheNames = configuration.getCacheNames();
    for (String name : cacheNames)
        if (namespace.equals(name)) {
            assistant.useCacheRef(name);
            break;
        }

    databaseId = super.getConfiguration().getDatabaseId();
    lang = super.getConfiguration().getDefaultScriptingLanuageInstance();

    //~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Table table = entityClass.getAnnotation(Table.class);
    if (table == null) {
        tableName = CaseFormatUtils.camelToUnderScore(entityClass.getSimpleName());
    } else {
        tableName = table.name();
    }

    ///~~~~~~~~~~~~~~~~~~~~~~
    idField = AnnotationUtils.findDeclaredFieldWithAnnoation(Id.class, entityClass);
    if (!sharded && (this.idField.isAnnotationPresent(GeneratedValue.class))
            && (((GeneratedValue) this.idField.getAnnotation(GeneratedValue.class))
                    .strategy() == GenerationType.UUID))
        columnFields.add(idField);
    else
        columnFields.add(idField);
    versionField = AnnotationUtils.findDeclaredFieldWithAnnoation(Version.class, entityClass);

    ReflectionUtils.doWithFields(entityClass, new FieldCallback() {

        public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
            if (field.isAnnotationPresent(Column.class))
                columnFields.add(field);
            if (field.isAnnotationPresent(Sn.class))
                containSn = true;

        }
    }, new FieldFilter() {

        public boolean matches(Field field) {
            if (Modifier.isStatic(field.getModifiers()) || Modifier.isFinal(field.getModifiers())) {
                return false;
            }

            for (Annotation annotation : field.getAnnotations()) {
                if (Transient.class.isAssignableFrom(annotation.getClass())
                        || Id.class.isAssignableFrom(annotation.getClass())) {
                    return false;
                }
            }

            return true;
        }
    });
}

From source file:adalid.core.Operation.java

private void finaliseParameter(Field field, Parameter parameter) {
    if (field == null || parameter == null) {
        return;/*from   w ww .  j  a  v  a2s  .c  om*/
    }
    String key = field.getName();
    if (key == null || _parameters.containsKey(key)) {
        return;
    }
    if (field.isAnnotationPresent(CastingField.class)) {
        if (parameter instanceof AbstractDataArtifact) {
            AbstractDataArtifact artifact = (AbstractDataArtifact) parameter;
            artifact.annotate(field);
        }
        return;
    }
    if (parameter.isNotDeclared()) {
        //          parameter.setDeclared(key, this, field);
        XS1.declare(parameter, this, field);
    }
    if (parameter instanceof Entity) {
        Entity entity = (Entity) parameter;
        if (!entity.isFinalised()) {
            entity.finalise();
        }
        Entity root = entity.getRoot();
        if (root != null) {
            root.getParameterReferencesMap().put(parameter.getPathString(), parameter);
        }
    }
    _parameters.put(key, parameter);
}

From source file:org.apache.nifi.registry.security.authorization.AuthorizerFactory.java

private void performFieldInjection(final Object 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);//ww w .  java2  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 (NiFiRegistryProperties.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:org.jdbcluster.domain.DomainCheckerImpl.java

/**
 * for package wide use//from w w  w  .j av a 2  s.  c  o m
 * 
 * @param cluster cluster instance
 * @param fSlave field of the slave domain
 * @param slaveValue the value to check
 * @param ddSlave the annotation
 * @return true if value is allowed
 */
boolean check(ICluster cluster, Field fSlave, String slaveValue, DomainDependancy ddSlave) {

    String slaveDomainId = getDomainIdFromField(fSlave, true);
    String propMasterPath = ddSlave.dependsFromProperty();

    Field fMaster = JDBClusterUtil.getField(propMasterPath, cluster);
    String masterDomainId = getDomainIdFromField(fMaster, false);

    String masterValue = (String) JDBClusterUtil.invokeGetPropertyMethod(ddSlave.dependsFromProperty(),
            cluster);

    // check if there are additional depenancies
    if (!fSlave.isAnnotationPresent(AddDomainDependancy.class))
        return check(masterDomainId, masterValue, slaveDomainId, slaveValue);

    AddDomainDependancy aDD = fSlave.getAnnotation(AddDomainDependancy.class);
    String[] addDomIdArr = new String[aDD.addDepFromProp().length];
    String[] addDomValArr = new String[aDD.addDepFromProp().length];
    for (int i = 0; i < aDD.addDepFromProp().length; i++) {

        Field faddMaster = JDBClusterUtil.getField(aDD.addDepFromProp()[i], cluster);
        String addMasterDomainId = getDomainIdFromField(faddMaster, false);

        addDomIdArr[i] = addMasterDomainId;
        addDomValArr[i] = (String) JDBClusterUtil.invokeGetPropertyMethod(aDD.addDepFromProp()[i], cluster);
    }
    return check(masterDomainId, masterValue, slaveDomainId, slaveValue, addDomIdArr, addDomValArr);
}