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.mybatisorm.annotation.handler.TableHandler.java

public List<ResultMapping> getResultMappingList(Configuration configuration) {
    List<ResultMapping> list = new ArrayList<ResultMapping>();
    for (Field field : getColumnFields()) {
        String columnName = ColumnAnnotation.getName(field);

        if (!"".equals(columnName)) {
            ResultMapping.Builder builder = new ResultMapping.Builder(configuration, field.getName(),
                    columnName, field.getType());
            // add typeHandler
            if (field.isAnnotationPresent(TypeHandler.class)) {
                TypeHandler typeHandlerAnnotation = field.getAnnotation(TypeHandler.class);
                // if (logger.isDebugEnabled()) logger.debug("add typeHandler [" + typeHandlerAnnotation.value().getName() + "] for " + columnName + ":" + typeHandlerAnnotation.jdbcType());
                builder.typeHandler(BeanUtils.instantiate(typeHandlerAnnotation.value()))
                        .jdbcType(typeHandlerAnnotation.jdbcType());

            }/*www  .  j  a  v a 2  s . co m*/
            list.add(builder.build());
        }
    }
    return list;
}

From source file:com.blackbear.flatworm.config.impl.DefaultAnnotationConfigurationReaderImpl.java

/**
 * Look through the given {@code clazz}'s {@link Field}s and see if there are any that have {@code annotations} that are supported by
 * flatworm and if so, process them./*www .j  ava  2 s. com*/
 *
 * @param record The {@link RecordBO} instance that is being built up - all processed data will get loaded to this {@link RecordBO}
 *               instance.
 * @param clazz  The {@link Class} to be interrogated.
 * @throws FlatwormConfigurationException should any of the configuration data be invalid.
 */
public void processFieldAnnotations(RecordBO record, Class<?> clazz) throws FlatwormConfigurationException {
    for (Field field : clazz.getDeclaredFields()) {
        // Check for RecordElement.
        if (field.isAnnotationPresent(RecordElement.class)) {
            loadRecordElement(record, clazz, field);
        } else if (field.isAnnotationPresent(SegmentElement.class)) {
            loadSegment(clazz, field);
        } else if (field.isAnnotationPresent(Line.class)) {
            Line annotatedLine = field.getAnnotation(Line.class);
            LineBO line = loadLine(annotatedLine);
            loadForProperty(annotatedLine.forProperty(), line);

            Class<?> fieldType = Util.getActualFieldType(field);
            line.getCardinality().setParentBeanRef(clazz.getName());
            line.getCardinality().setBeanRef(fieldType.getName());
            line.getCardinality().setPropertyName(field.getName());

            addBeanToRecord(clazz, record);
            addBeanToRecord(fieldType, record);

            if (line.getCardinality().getCardinalityMode() == CardinalityMode.AUTO_RESOLVE) {
                line.getCardinality().setCardinalityMode(ParseUtils.resolveCardinality(field.getType()));
            }

            record.getRecordDefinition().addLine(line);

            lineElementDeque.add(line);
            processFieldAnnotations(record, fieldType);
            lineElementDeque.removeLast();
        }
    }
}

From source file:org.ambient.control.config.EditConfigFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    // integrate object into existing configuration after child fragment has data left for us via onIntegrate. We do the
    // integration here after the arguments and bundles have been restored. We cannot merge the values in onCreate() because
    // it will only be called from android when the fragment instance has been removed before. e.g. screen rotation.
    if (this.valueToIntegrate != null) {
        this.integrateConfiguration(this.valueToIntegrate);
    }//from w w w  .  j  av  a  2s .  co m

    try {

        ScrollView result = (ScrollView) inflater.inflate(R.layout.fragment_edit_config, container, false);

        LinearLayout content = (LinearLayout) result.findViewById(R.id.linearLayoutEditConfigContent);

        // init the maps for grouped and sorted fields
        Map<Integer, Map<Integer, Field>> sortedMap = new TreeMap<Integer, Map<Integer, Field>>();
        // and a simple list for those fields which have no sort description
        List<Field> unsortedList = new ArrayList<Field>();

        // create groups if class description is present and defines some
        ClassDescription description = beanToEdit.getClass().getAnnotation(ClassDescription.class);
        if (description != null) {
            for (Group currentGroup : description.groups()) {
                Map<Integer, Field> category = new TreeMap<Integer, Field>();
                sortedMap.put(currentGroup.position(), category);
            }
        } else {
            // create a default group
            sortedMap.put(0, new TreeMap<Integer, Field>());
        }

        // sort fields that are annotated in groups
        for (final Field field : beanToEdit.getClass().getFields()) {
            // only use field with typedef annotation. the rest of the
            // fields will be ignored
            if (field.isAnnotationPresent(TypeDef.class)) {
                if (field.isAnnotationPresent(Presentation.class)) {
                    // put into groups
                    Presentation presentation = field.getAnnotation(Presentation.class);
                    sortedMap.get(presentation.groupPosition()).put(presentation.position(), field);
                } else {
                    // or to unsorted group if no information for sorting is
                    // present
                    unsortedList.add(field);
                }
            }
        }

        // if no sorted values haven been drawn we create a default group on
        // screen and put all unsorted values in there. if some have been
        // drawn we put them into a "misc" group. we could do a check at the
        // beginning if several groups have been filled and so on. but we
        // render them first and get the information as result of that.
        boolean sortedValuesDrawn = false;

        for (Integer currentCategoryId : sortedMap.keySet()) {
            if (sortedMap.get(currentCategoryId).isEmpty()) {
                continue;
            }

            LinearLayout categoryView = (LinearLayout) inflater.inflate(R.layout.layout_editconfig_group_header,
                    null);
            TextView title = (TextView) categoryView.findViewById(R.id.textViewGroupHeader);
            TextView descriptionTextView = (TextView) categoryView.findViewById(R.id.textViewGroupDescription);
            content.addView(categoryView);

            if (currentCategoryId == 0) {
                // draw allgemein for category 0. if an group with id 0 is
                // described the values will be overwritten in next step
                title.setText("ALLGEMEIN");
                descriptionTextView.setVisibility(View.GONE);
            }

            // draw the category header and a description if present
            if (description != null) {
                for (Group currentGroup : description.groups()) {
                    if (currentGroup.position() == currentCategoryId) {
                        title.setText(currentGroup.name());
                        if (currentGroup.description().isEmpty() == false) {
                            descriptionTextView.setText(currentGroup.description());
                            descriptionTextView.setVisibility(View.VISIBLE);
                        } else {
                            descriptionTextView.setVisibility(View.GONE);
                        }
                        break;
                    }
                }
            }

            // draw all handlers for the fields in this category
            Map<Integer, Field> values = sortedMap.get(currentCategoryId);
            for (Field field : values.values()) {
                addFieldToView(inflater, beanToEdit, content, field);

                // we are shure that the default or a special category have
                // been used. if there are unsorted values put them into an
                // additional group later
                sortedValuesDrawn = true;
            }
        }

        // draw a header for unsorted fields if class description provided
        // categories for the other fields
        if (sortedValuesDrawn && unsortedList.isEmpty() == false) {
            LinearLayout categoryFurther = (LinearLayout) inflater
                    .inflate(R.layout.layout_editconfig_group_header, null);
            TextView title = (TextView) categoryFurther.findViewById(R.id.textViewGroupHeader);
            title.setText("WEITERE");
            TextView descriptionTextView = (TextView) categoryFurther
                    .findViewById(R.id.textViewGroupDescription);
            descriptionTextView.setVisibility(View.GONE);
            content.addView(categoryFurther);
        }

        // draw the handlers
        for (Field currentField : unsortedList) {
            addFieldToView(inflater, beanToEdit, content, currentField);
        }

        // default text if no fields are annotated
        if (sortedValuesDrawn == false && unsortedList.isEmpty()) {
            TextView tv = new TextView(content.getContext());
            tv.setText("Dieses Objekt wird nicht konfiguriert");
            content.addView(tv);
        }

        return result;

    } catch (Exception e) {
        Log.e(LOG, "could not create View for bean: " + beanToEdit.getClass().getName(), e);
        return null;
    }
}

From source file:org.apdplat.platform.action.ExtJSSimpleAction.java

private void addFieldValue(T obj, Field field, Map<String, String> data) {
    String fieldName = field.getName();
    try {/*  www  .  j a va 2s  .  c o m*/
        if (field.isAnnotationPresent(Lob.class)) {
            LOG.debug("[" + fieldName + "]?JSON");
            return;
        }
        Object value = ReflectionUtils.getFieldValue(obj, field);
        if (value == null) {
            data.put(fieldName, "");
            return;
        }
        //??
        if (field.isAnnotationPresent(ModelCollRef.class)) {
            ModelCollRef ref = field.getAnnotation(ModelCollRef.class);
            String fieldRef = ref.value();
            Collection col = (Collection) value;
            String colStr = "";
            if (col != null) {
                LOG.debug("??," + field.getName() + ",?" + col.size());
                if (col.size() > 0) {
                    StringBuilder str = new StringBuilder();
                    for (Object m : col) {
                        str.append(ReflectionUtils.getFieldValue(m, fieldRef).toString()).append(",");
                    }
                    str = str.deleteCharAt(str.length() - 1);
                    colStr = str.toString();
                }
            } else {
                LOG.debug("??" + value + " ???");
            }
            data.put(fieldName, colStr);
            return;
        }
        //???
        if (field.isAnnotationPresent(ModelAttrRef.class)) {
            LOG.debug("?," + field.getName());
            ModelAttrRef ref = field.getAnnotation(ModelAttrRef.class);
            String fieldRef = ref.value();
            //??ID
            Object id = ReflectionUtils.getFieldValue(value, "id");
            data.put(fieldName + "_id", id.toString());
            //??????
            fieldName = fieldName + "_" + fieldRef;
            //?fieldRef
            value = ReflectionUtils.getFieldValue(value, fieldRef);
        }
        if (value.getClass() == null) {
            data.put(fieldName, "");
            return;
        }
        String valueClass = value.getClass().getSimpleName();

        if ("PersistentBag".equals(valueClass)) {
            value = "";
        }
        if ("Timestamp".equals(valueClass) || "Date".equals(valueClass)) {
            if (field.isAnnotationPresent(RenderDate.class)) {
                value = DateTypeConverter.toDefaultDate((Date) value);
            } else if (field.isAnnotationPresent(RenderTime.class)) {
                value = DateTypeConverter.toDefaultDateTime((Date) value);
            } else {
                //?@Temporal?
                String temporal = "TIMESTAMP";
                if (field.isAnnotationPresent(Temporal.class)) {
                    temporal = field.getAnnotation(Temporal.class).value().name();
                }
                switch (temporal) {
                case "TIMESTAMP":
                    value = DateTypeConverter.toDefaultDateTime((Date) value);
                    break;
                case "DATE":
                    value = DateTypeConverter.toDefaultDate((Date) value);
                    break;
                }
            }
        }
        //???
        if ("DicItem".equals(valueClass)) {
            //??
            data.put(fieldName + "Id", ReflectionUtils.getFieldValue(value, "id").toString());

            value = ReflectionUtils.getFieldValue(value, "name");
        }
        data.put(fieldName, value.toString());
    } catch (Exception e) {
        LOG.error("?", e);
    }
}

From source file:org.alfresco.po.PageElement.java

/**
 * Waits for given {@link ElementState} of all render elements when rendering a page.
 * If the given element not reach element state, it will time out and throw {@link TimeoutException}. 
 * If operation to find all elements times out a {@link PageRenderTimeException} is thrown
 * Renderable elements will be scanned from class using {@link RenderWebElement} annotation.
 *
 * @param renderTime render timer/*from   www.j  a va  2  s . com*/
 * @throws IllegalAccessException 
 * @throws IllegalArgumentException 
 */
public void webElementRender(RenderTime renderTime) {
    if (renderTime == null) {
        throw new UnsupportedOperationException("RenderTime is required");
    }
    List<RenderElement> elements = new ArrayList<RenderElement>();
    Field[] fields = this.getClass().getDeclaredFields();
    for (Field field : fields) {
        if (field.isAnnotationPresent(RenderWebElement.class)) {
            Class<?> type = field.getType();
            field.setAccessible(true);
            Object fieldVal = null;
            try {
                fieldVal = field.get(this);
            } catch (IllegalArgumentException | IllegalAccessException e) {
                logger.error("Unable to set field", e);
            }

            //Handle page elements, extracts the @FindBy from the component.
            if (PageElement.class.isAssignableFrom(type)) {
                Annotation a = type.getAnnotation(FindBy.class);
                if (a != null) {
                    try {
                        By by = buildFromFindBy((FindBy) a);
                        elements.add(new RenderElement(by, ElementState.VISIBLE));
                    } catch (Exception ex) {
                    }
                }
            }
            if (type.equals(By.class)) {
                /*FIXME Below is the old way which we need to remove and use the web element instead.
                 *This is kept until we refactor the sharepo to use webelement instead of
                 *By.class. 
                 * @RenderWebelement By css = By.cssSelector("div.t");
                 * to 
                 * @RenderWebelement WebElement css;
                 * 
                 */
                RenderWebElement webElement = (RenderWebElement) field.getAnnotation(RenderWebElement.class);
                elements.add(new RenderElement((By) fieldVal, webElement.state()));
            } else {
                Annotation[] list = field.getDeclaredAnnotations();
                By by = null;
                for (Annotation a : list) {
                    if (a instanceof FindBy) {
                        by = extractSelector((FindBy) a);
                    }
                }
                if (by != null) {
                    elements.add(new RenderElement(by, ElementState.VISIBLE));
                }
            }
        }
    }
    if (!elements.isEmpty()) {
        elementRender(renderTime, elements.toArray(new RenderElement[elements.size()]));
    }
}

From source file:com.opensymphony.xwork2.util.finder.ClassFinder.java

public List<Field> findAnnotatedFields(Class<? extends Annotation> annotation) {
    classesNotLoaded.clear();/*w w  w  .  j  a v  a  2  s.co  m*/
    List<ClassInfo> seen = new ArrayList<ClassInfo>();
    List<Field> fields = new ArrayList<Field>();
    List<Info> infos = getAnnotationInfos(annotation.getName());
    for (Info info : infos) {
        if (info instanceof FieldInfo) {
            FieldInfo fieldInfo = (FieldInfo) info;
            ClassInfo classInfo = fieldInfo.getDeclaringClass();

            if (seen.contains(classInfo))
                continue;

            seen.add(classInfo);

            try {
                Class clazz = classInfo.get();
                for (Field field : clazz.getDeclaredFields()) {
                    if (field.isAnnotationPresent(annotation)) {
                        fields.add(field);
                    }
                }
            } catch (Throwable e) {
                if (LOG.isErrorEnabled())
                    LOG.error("Error loading class [#0]", e, classInfo.getName());
                classesNotLoaded.add(classInfo.getName());
            }
        }
    }
    return fields;
}

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

private ArrayList<Field> getOrmobjectUsableFields() {
    ArrayList<Field> result = new ArrayList<Field>();

    Field[] fields = this.reference.getFields();
    Field field;
    int mod;//from w  ww . j a  va  2s.c o m
    for (int pos_df = 0; pos_df < fields.length; pos_df++) {
        field = fields[pos_df];
        if (field.isAnnotationPresent(Transient.class)) {
            /**
             * Is transient ?
             */
            continue;
        }
        if (field.getName().equals("key")) {
            /**
             * Not this (primary key)
             */
            continue;
        }
        mod = field.getModifiers();

        if ((mod & Modifier.PROTECTED) != 0)
            continue;
        if ((mod & Modifier.PRIVATE) != 0)
            continue;
        if ((mod & Modifier.ABSTRACT) != 0)
            continue;
        if ((mod & Modifier.STATIC) != 0)
            continue;
        if ((mod & Modifier.FINAL) != 0)
            continue;
        if ((mod & Modifier.TRANSIENT) != 0)
            continue;
        if ((mod & Modifier.INTERFACE) != 0)
            continue;

        try {
            result.add(field);
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        }
    }

    return result;
}

From source file:com.boylesoftware.web.impl.UserInputControllerMethodArgHandler.java

/**
 * Create new handler.//w ww.j  a  v a  2 s.c om
 *
 * @param validatorFactory Validator factory.
 * @param beanClass User input bean class.
 * @param validationGroups Validation groups to apply during bean
 * validation, or empty array to use the default group.
 *
 * @throws UnavailableException If an error happens.
 */
UserInputControllerMethodArgHandler(final ValidatorFactory validatorFactory, final Class<?> beanClass,
        final Class<?>[] validationGroups) throws UnavailableException {

    this.validatorFactory = validatorFactory;

    this.beanClass = beanClass;
    this.validationGroups = validationGroups;

    try {
        final BeanInfo beanInfo = Introspector.getBeanInfo(this.beanClass);
        final PropertyDescriptor[] propDescs = beanInfo.getPropertyDescriptors();
        final List<FieldDesc> beanFields = new ArrayList<>();
        for (final PropertyDescriptor propDesc : propDescs) {
            final String propName = propDesc.getName();
            final Class<?> propType = propDesc.getPropertyType();
            final Method propGetter = propDesc.getReadMethod();
            final Method propSetter = propDesc.getWriteMethod();

            if ((propGetter == null) || (propSetter == null))
                continue;

            Field propField = null;
            for (Class<?> c = this.beanClass; !c.equals(Object.class); c = c.getSuperclass()) {
                try {
                    propField = c.getDeclaredField(propName);
                    break;
                } catch (final NoSuchFieldException e) {
                    // nothing, continue the loop
                }
            }
            final boolean noTrim = (((propField != null) && propField.isAnnotationPresent(NoTrim.class))
                    || (propGetter.isAnnotationPresent(NoTrim.class)));

            Class<? extends Binder> binderClass = null;
            String format = null;
            String errorMessage = Bind.DEFAULT_MESSAGE;
            Bind bindAnno = null;
            if (propField != null)
                bindAnno = propField.getAnnotation(Bind.class);
            if (bindAnno == null)
                bindAnno = propGetter.getAnnotation(Bind.class);
            if (bindAnno != null) {
                binderClass = bindAnno.binder();
                format = bindAnno.format();
                errorMessage = bindAnno.message();
            }
            if (binderClass == null) {
                if ((String.class).isAssignableFrom(propType))
                    binderClass = StringBinder.class;
                else if ((Boolean.class).isAssignableFrom(propType) || propType.equals(Boolean.TYPE))
                    binderClass = BooleanBinder.class;
                else if ((Integer.class).isAssignableFrom(propType) || propType.equals(Integer.TYPE))
                    binderClass = IntegerBinder.class;
                else if (propType.isEnum())
                    binderClass = EnumBinder.class;
                else // TODO: add more standard binders
                    throw new UnavailableException(
                            "Unsupported user input bean field type " + propType.getName() + ".");
            }

            beanFields.add(new FieldDesc(propDesc, noTrim, binderClass.newInstance(), format, errorMessage));
        }
        this.beanFields = beanFields.toArray(new FieldDesc[beanFields.size()]);
    } catch (final IntrospectionException e) {
        this.log.error("error introspecting user input bean", e);
        throw new UnavailableException("Specified user input bean" + " class could not be introspected.");
    } catch (final IllegalAccessException | InstantiationException e) {
        this.log.error("error instatiating binder", e);
        throw new UnavailableException("Used user input bean field binder" + " could not be instantiated.");
    }

    this.beanPool = new FastPool<>(new PoolableObjectFactory<PoolableUserInput>() {

        @Override
        public PoolableUserInput makeNew(final FastPool<PoolableUserInput> pool, final int pooledObjectId) {

            try {
                return new PoolableUserInput(pool, pooledObjectId, beanClass.newInstance());
            } catch (final InstantiationException | IllegalAccessException e) {
                throw new RuntimeException("Error instatiating user input bean.", e);
            }
        }
    }, "UserInputBeansPool_" + beanClass.getSimpleName());
}

From source file:com.haulmont.cuba.core.sys.MetaModelLoader.java

protected boolean isMetaPropertyField(Field field) {
    return field.isAnnotationPresent(Column.class) || field.isAnnotationPresent(ManyToOne.class)
            || field.isAnnotationPresent(OneToMany.class) || field.isAnnotationPresent(ManyToMany.class)
            || field.isAnnotationPresent(OneToOne.class) || field.isAnnotationPresent(Embedded.class)
            || field.isAnnotationPresent(EmbeddedId.class)
            || field.isAnnotationPresent(com.haulmont.chile.core.annotations.MetaProperty.class);
}

From source file:com.haulmont.cuba.core.sys.MetaModelLoader.java

protected Range.Cardinality getCardinality(Field field) {
    if (field.isAnnotationPresent(Column.class)) {
        return Range.Cardinality.NONE;
    } else if (field.isAnnotationPresent(OneToOne.class)) {
        return Range.Cardinality.ONE_TO_ONE;
    } else if (field.isAnnotationPresent(OneToMany.class)) {
        return Range.Cardinality.ONE_TO_MANY;
    } else if (field.isAnnotationPresent(ManyToOne.class)) {
        return Range.Cardinality.MANY_TO_ONE;
    } else if (field.isAnnotationPresent(ManyToMany.class)) {
        return Range.Cardinality.MANY_TO_MANY;
    } else if (field.isAnnotationPresent(Embedded.class)) {
        return Range.Cardinality.ONE_TO_ONE;
    } else {/*from  w w  w.j ava 2  s  . c o  m*/
        Class<?> type = field.getType();
        if (Collection.class.isAssignableFrom(type)) {
            return Range.Cardinality.ONE_TO_MANY;
        } else if (type.isPrimitive() || type.equals(String.class) || Number.class.isAssignableFrom(type)
                || Date.class.isAssignableFrom(type) || UUID.class.isAssignableFrom(type)) {
            return Range.Cardinality.NONE;
        } else
            return Range.Cardinality.MANY_TO_ONE;
    }
}