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:net.openj21.mih.protocol.codec.AnnotationUtils.java

/**
 * Returns a Collection containing all fields of the given SEQUENCE class
 * that are annotated with the SEQUENCE_ELEMENT annotation. The collection
 * is sorted on the order of the sequence elements.
 *
 * @param sequenceClass a class/*from  www  .  j  a v a 2 s.  c  om*/
 * @return a Collection containing all fields of the given SEQUENCE class
 */
public Collection<Field> getSequenceFields(Class<?> sequenceClass) {
    final SortedMap<Integer, Field> toEncodeFields = new TreeMap<Integer, Field>();
    ReflectionUtils.doWithFields(sequenceClass, new ReflectionUtils.FieldCallback() {

        public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
            SEQUENCE_ELEMENT encodedAnnotation = field.getAnnotation(SEQUENCE_ELEMENT.class);
            if (encodedAnnotation != null) {
                if (toEncodeFields.put(encodedAnnotation.order(), field) != null) {
                    throw new IllegalStateException(
                            "Duplicate " + SEQUENCE_ELEMENT.class.getSimpleName() + " order: " + field);
                }
            }
        }
    });

    return toEncodeFields.values();
}

From source file:com.cognifide.aemrules.extensions.RulesLoader.java

private void loadParameters(RulesDefinition.NewRule rule, Field field) {
    org.sonar.check.RuleProperty propertyAnnotation = field.getAnnotation(org.sonar.check.RuleProperty.class);
    if (propertyAnnotation != null) {
        String fieldKey = StringUtils.defaultIfEmpty(propertyAnnotation.key(), field.getName());
        RulesDefinition.NewParam param = rule.createParam(fieldKey)
                .setDescription(propertyAnnotation.description())
                .setDefaultValue(propertyAnnotation.defaultValue());

        if (!StringUtils.isBlank(propertyAnnotation.type())) {
            try {
                param.setType(RuleParamType.parse(propertyAnnotation.type().trim()));
            } catch (IllegalArgumentException e) {
                throw new IllegalArgumentException("Invalid property type [" + propertyAnnotation.type() + "]",
                        e);/*from  w w  w  . ja  v  a2 s . c o m*/
            }
        } else {
            param.setType(guessType(field.getType()));
        }
    }
}

From source file:com.nabla.wapp.server.database.UpdateStatement.java

@SuppressWarnings("unchecked")
private IRecordTable commonConstructor(final Class clazz) {
    if (clazz == null)
        return null;
    final IRecordTable t = (IRecordTable) clazz.getAnnotation(IRecordTable.class);
    for (Field field : clazz.getDeclaredFields()) {
        final IRecordField definition = field.getAnnotation(IRecordField.class);
        if (definition == null)
            continue;
        if (definition.id())
            recordId = createParameter(field);
        else {/*from  w ww .j ava 2  s. c  o m*/
            if (definition.unique())
                uniqueFieldName = field.getName();
            parameters.add(createParameter(field));
        }
    }
    final IRecordTable tt = commonConstructor(clazz.getSuperclass());
    return (t == null) ? tt : t;
}

From source file:com.comcast.video.dawg.show.plugins.PluginController.java

/**
 * Gets the config and display map. Display map is a mapping from field name to how the field
 * should be displayed in the UI//w  w w.  j a  va2s  .c  o m
 * @param remoteType The remote type that identifies what plugin to get
 * @return
 * @throws IOException
 */
@SuppressWarnings({ "unchecked" })
@RequestMapping(method = { RequestMethod.GET }, value = "/plugins/remote/cdm/{remoteType}")
@ResponseBody
public Map<String, Object> getPluginConfigAndDisplayMap(@PathVariable String remoteType) throws IOException {
    PluginConfiguration config = getRemotePlugin(remoteType);
    if (config == null)
        return null;
    Map<String, String> displayMap = new HashMap<String, String>();
    Set<Field> fields = ReflectionUtils.getFields(config.getClass(),
            ReflectionUtils.withAnnotation(PluginConfigValue.class));
    for (Field field : fields) {
        String disp = field.getAnnotation(PluginConfigValue.class).display();
        if (StringUtils.isEmpty(disp)) {
            disp = field.getName();
        }
        displayMap.put(field.getName(), disp);
    }
    Map<String, Object> configAndDM = new HashMap<>();
    configAndDM.put("config", config);
    configAndDM.put("displayMap", displayMap);
    return configAndDM;
}

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

public final void process(final Class<?> clazz, EntityMetadata metadata) {

    metadata.setIndexName(clazz.getSimpleName());

    Index idx = clazz.getAnnotation(Index.class);
    if (null != idx) {
        boolean isIndexable = idx.index();
        metadata.setIndexable(isIndexable);

        if (!isIndexable) {
            log.debug("@Entity " + clazz.getName() + " will not be indexed.");
            return;
        }/* w  w w .j  a  v a 2  s  .com*/
    }

    log.debug("Processing @Entity " + clazz.getName() + " for Indexes.");

    // scan for fields
    for (Field f : clazz.getDeclaredFields()) {
        if (f.isAnnotationPresent(Column.class)) {
            Column c = f.getAnnotation(Column.class);
            String alias = c.name().trim();
            if (alias.isEmpty()) {
                alias = f.getName();
            }

            metadata.addIndexProperty(metadata.new PropertyIndex(f, alias));

        } else if (f.isAnnotationPresent(Id.class)) {
            metadata.addIndexProperty(metadata.new PropertyIndex(f, f.getName()));
        }
    }
}

From source file:com.nabla.wapp.server.database.InsertStatement.java

@SuppressWarnings("unchecked")
private IRecordTable commonConstructor(final Class clazz) {
    if (clazz == null)
        return null;
    final IRecordTable t = (IRecordTable) clazz.getAnnotation(IRecordTable.class);
    for (Field field : clazz.getDeclaredFields()) {
        final IRecordField definition = field.getAnnotation(IRecordField.class);
        if (definition == null)
            continue;
        if (definition.unique())
            uniqueFieldName = field.getName();
        parameters.add(createParameter(field));
    }//from  w ww.  j a  v  a 2  s .c  o m
    final IRecordTable tt = commonConstructor(clazz.getSuperclass());
    return (t == null) ? tt : t;
}

From source file:com.liferay.portal.spring.extender.internal.bean.ServiceReferenceAnnotationBeanPostProcessor.java

protected void autoInject(Object targetBean, Class<?> beanClass) {
    if ((beanClass == null) || beanClass.isInterface()) {
        return;/*from w  w  w  .j  av  a  2 s .co m*/
    }

    Field[] fields = beanClass.getDeclaredFields();

    for (Field field : fields) {
        ServiceReference serviceReference = field.getAnnotation(ServiceReference.class);

        if (serviceReference == null) {
            continue;
        }

        org.osgi.framework.ServiceReference<?> osgiServiceReference = null;

        try {
            String filterString = serviceReference.filterString();

            if (filterString.isEmpty()) {
                Class<?> typeClass = serviceReference.type();

                osgiServiceReference = _bundleContext.getServiceReference(typeClass.getName());
            } else {
                Class<?> typeClass = serviceReference.type();

                org.osgi.framework.ServiceReference<?>[] serviceReferences = _bundleContext
                        .getServiceReferences(typeClass.getName(), filterString);

                if (serviceReferences != null) {
                    osgiServiceReference = serviceReferences[0];
                }
            }

            ReflectionUtils.makeAccessible(field);

            field.set(targetBean, _bundleContext.getService(osgiServiceReference));
        } catch (Throwable t) {
            throw new BeanCreationException(beanClass.getName(), "Unable to inject bean reference fields", t);
        }

        _serviceReferences.add(osgiServiceReference);
    }

    autoInject(targetBean, beanClass.getSuperclass());
}

From source file:net.kamhon.ieagle.util.VoUtil.java

/**
 * To trim object String field/*w  ww. j a  v a  2  s .  c  o m*/
 * 
 * @param all
 *            default is false. true means toTrim all String field, false toTrim the fields have
 *            net.kamhon.ieagle.vo.core.annotation.ToTrim.
 * 
 * @param objects
 */
public static void toTrimProperties(boolean all, Object... objects) {
    for (Object object : objects) {
        if (object == null) {
            continue;
        }

        // getter for String field only
        Map<String, Method> getterMap = new HashMap<String, Method>();
        // setter for String field only
        Map<String, Method> setterMap = new HashMap<String, Method>();

        Class<?> clazz = object.getClass();

        Method[] methods = clazz.getMethods();

        for (Method method : methods) {
            if (method.getName().startsWith("get") && method.getParameterTypes().length == 0
                    && method.getReturnType().equals(String.class)) {

                // if method name is getXxx
                String fieldName = method.getName().substring(3);
                fieldName = fieldName.substring(0, 1).toLowerCase() + fieldName.substring(1);

                getterMap.put(fieldName, method);
            } else if (method.getName().startsWith("set") && method.getParameterTypes().length == 1
                    && method.getParameterTypes()[0] == String.class
                    && method.getReturnType().equals(void.class)) {
                // log.debug("setter = " + method.getName());

                // if method name is setXxx
                String fieldName = method.getName().substring(3);
                fieldName = fieldName.substring(0, 1).toLowerCase() + fieldName.substring(1);

                setterMap.put(fieldName, method);
            }
        }

        // if the key exists in both getter & setter
        for (String key : getterMap.keySet()) {
            if (setterMap.containsKey(key)) {
                try {
                    Method getterMethod = getterMap.get(key);
                    Method setterMethod = setterMap.get(key);

                    // if not all, check on Field
                    if (!all) {
                        Field field = null;

                        Class<?> tmpClazz = clazz;
                        // looping up to superclass to get decleared field
                        do {
                            try {
                                field = tmpClazz.getDeclaredField(key);
                            } catch (Exception ex) {
                                // do nothing
                            }

                            if (field != null) {
                                break;
                            }

                            tmpClazz = tmpClazz.getSuperclass();
                        } while (tmpClazz != null);

                        ToTrim toTrim = field.getAnnotation(ToTrim.class);
                        if (toTrim == null || toTrim.trim() == false) {
                            continue;
                        }
                    }

                    String value = (String) getterMethod.invoke(object, new Object[] {});

                    if (StringUtils.isNotBlank(value))
                        setterMethod.invoke(object, value.trim());

                } catch (Exception ex) {
                    // log.error("Getter Setter for " + key + " has error ", ex);
                }
            }
        }
    }
}

From source file:com.nabla.wapp.server.database.SqlInsert.java

protected void buildParameterList(final Class clazz) {
    if (clazz != null) {
        for (Field field : clazz.getDeclaredFields()) {
            final IRecordField definition = field.getAnnotation(IRecordField.class);
            if (definition != null)
                parameters.add(SqlStatement.createParameter(field));
        }/*w  w  w  . j a v a 2  s.co m*/
        buildParameterList(clazz.getSuperclass());
    }
}

From source file:de.hsos.ecs.richwps.wpsmonitor.boundary.cli.command.annotation.CommandAnnotationProcessor.java

private void addOptions(final Command cmd) throws CommandAnnotationProcessorException {
    final List<Field> fields = getFields(cmd.getClass());

    for (final Field field : fields) {
        final CommandOption annotation = field.getAnnotation(CommandOption.class);

        if (annotation != null) {
            final String longOpt = annotation.longOptionName().equals("") ? null : annotation.longOptionName();

            Option option = new Option(annotation.shortOptionName(), longOpt, annotation.hasArgument(),
                    annotation.description());

            if (annotation.hasArgument()) {
                option.setArgName(annotation.argumentName());
            } else {
                if (!field.getType().equals(Boolean.class)) {
                    throw new CommandAnnotationProcessorException(
                            "If the Option has no argument, the field must be of type boolean.");
                }/*from   w ww .  j  a v a 2 s  . c  o  m*/
            }

            option.setOptionalArg(annotation.optionalArgument());

            cmd.addOption(option);
        }
    }
}