Example usage for java.lang Class getDeclaredFields

List of usage examples for java.lang Class getDeclaredFields

Introduction

In this page you can find the example usage for java.lang Class getDeclaredFields.

Prototype

@CallerSensitive
public Field[] getDeclaredFields() throws SecurityException 

Source Link

Document

Returns an array of Field objects reflecting all the fields declared by the class or interface represented by this Class object.

Usage

From source file:eu.eubrazilcc.lvl.core.util.QueryUtils.java

public static List<FormattedQueryParam> formattedQuery(final ImmutableMap<String, String> params,
        final Class<?> target) {
    checkArgument(params != null, "Uninitialized parameters");
    checkArgument(target != null, "Uninitialized target class");
    final Field[] fields = target.getDeclaredFields();
    final Function<String, Boolean> fieldValidator = new Function<String, Boolean>() {
        @Override//ww  w .  j a v  a  2s.  c  o m
        public Boolean apply(final String name) {
            for (final Field field : fields) {
                if (field.getName().equalsIgnoreCase(name)) {
                    return true;
                }
            }
            return false;
        }
    };
    return newArrayList(transformEntries(params, new EntryTransformer<String, String, FormattedQueryParam>() {
        @Override
        public FormattedQueryParam transformEntry(final String key, final String value) {
            final boolean isField = !TEXT_FIELD.equals(key);
            return FormattedQueryParam.builder()
                    .term((isField ? escape(key) + KEYWORD_SEPARATOR : "") + escape(value))
                    .validity(isField ? fieldValidator.apply(key) : true).build();
        }
    }).values());
}

From source file:net.elsched.utils.SettingsBinder.java

/**
 * Bind configuration parameters into Guice Module.
 * //from  w w w  . j  a v  a 2  s  .com
 * @return a Guice module configured with setting support.
 * @throws ConfigurationException
 *             on configuration error
 */
public static Module bindSettings(String propertiesFileKey, Class<?>... settingsArg)
        throws ConfigurationException {
    final CompositeConfiguration config = new CompositeConfiguration();
    config.addConfiguration(new SystemConfiguration());
    String propertyFile = config.getString(propertiesFileKey);

    if (propertyFile != null) {
        config.addConfiguration(new PropertiesConfiguration(propertyFile));
    }

    List<Field> fields = new ArrayList<Field>();
    for (Class<?> settings : settingsArg) {
        fields.addAll(Arrays.asList(settings.getDeclaredFields()));
    }

    // Reflect on settings class and absorb settings
    final Map<Setting, Field> settings = new LinkedHashMap<Setting, Field>();
    for (Field field : fields) {
        if (!field.isAnnotationPresent(Setting.class)) {
            continue;
        }

        // Validate target type
        SettingTypeValidator typeHelper = supportedSettingTypes.get(field.getType());
        if (typeHelper == null || !typeHelper.check(field.getGenericType())) {
            throw new IllegalArgumentException(field.getType() + " is not one of the supported setting types");
        }

        Setting setting = field.getAnnotation(Setting.class);
        settings.put(setting, field);
    }

    // Now validate them
    List<String> missingProperties = new ArrayList<String>();
    for (Setting setting : settings.keySet()) {
        if (setting.defaultValue().isEmpty()) {
            if (!config.containsKey(setting.name())) {
                missingProperties.add(setting.name());
            }
        }
    }
    if (missingProperties.size() > 0) {
        StringBuilder error = new StringBuilder();
        error.append("The following required properties are missing from the server configuration: ");
        error.append(Joiner.on(", ").join(missingProperties));
    }

    // bundle everything up in an injectable guice module
    return new AbstractModule() {

        @Override
        protected void configure() {
            // We must iterate the settings a third time when binding.
            // Note: do not collapse these loops as that will damage
            // early error detection. The runtime is still O(n) in setting
            // count.
            for (Map.Entry<Setting, Field> entry : settings.entrySet()) {
                Class<?> type = entry.getValue().getType();
                Setting setting = entry.getKey();

                if (int.class.equals(type)) {
                    Integer defaultValue = null;
                    if (!setting.defaultValue().isEmpty()) {
                        defaultValue = Integer.parseInt(setting.defaultValue());
                    }
                    bindConstant().annotatedWith(Names.named(setting.name()))
                            .to(config.getInteger(setting.name(), defaultValue));
                } else if (boolean.class.equals(type)) {
                    Boolean defaultValue = null;
                    if (!setting.defaultValue().isEmpty()) {
                        defaultValue = Boolean.parseBoolean(setting.defaultValue());
                    }
                    bindConstant().annotatedWith(Names.named(setting.name()))
                            .to(config.getBoolean(setting.name(), defaultValue));
                } else if (String.class.equals(type)) {
                    bindConstant().annotatedWith(Names.named(setting.name()))
                            .to(config.getString(setting.name(), setting.defaultValue()));
                } else {
                    String[] value = config.getStringArray(setting.name());
                    if (value.length == 0 && !setting.defaultValue().isEmpty()) {
                        value = setting.defaultValue().split(",");
                    }
                    bind(new TypeLiteral<List<String>>() {
                    }).annotatedWith(Names.named(setting.name())).toInstance(ImmutableList.copyOf(value));
                }
            }
        }
    };
}

From source file:com.sonatype.security.ldap.api.DeepEqualsBuilder.java

private static void reflectionAppend(Object lhs, Object rhs, Class clazz, EqualsBuilder builder,
        boolean useTransients, String[] excludeFields) {
    while (clazz.getSuperclass() != null) {

        Field[] fields = clazz.getDeclaredFields();
        List excludedFieldList = excludeFields != null ? Arrays.asList(excludeFields) : Collections.EMPTY_LIST;
        AccessibleObject.setAccessible(fields, true);
        for (int i = 0; i < fields.length && builder.isEquals(); i++) {
            Field f = fields[i];/*from   ww  w  . j  a va 2  s.c o  m*/
            if (!excludedFieldList.contains(f.getName()) && (f.getName().indexOf('$') == -1)
                    && (useTransients || !Modifier.isTransient(f.getModifiers()))
                    && (!Modifier.isStatic(f.getModifiers()))) {
                try {
                    Object lhsChild = f.get(lhs);
                    Object rhsChild = f.get(rhs);
                    Class testClass = getTestClass(lhsChild, rhsChild);
                    boolean hasEqualsMethod = classHasEqualsMethod(testClass);

                    if (testClass != null && !hasEqualsMethod) {
                        reflectionAppend(lhsChild, rhsChild, testClass, builder, useTransients, excludeFields);
                    } else {
                        builder.append(lhsChild, rhsChild);
                    }
                } catch (IllegalAccessException e) {
                    // this can't happen. Would get a Security exception instead
                    // throw a runtime exception in case the impossible happens.
                    throw new InternalError("Unexpected IllegalAccessException");
                }
            }
        }

        // now for the parent
        clazz = clazz.getSuperclass();
        reflectionAppend(lhs, rhs, clazz, builder, useTransients, excludeFields);
    }
}

From source file:com.test.edusys.common.utils.reflection.ReflectionUtils.java

/**
 * Comment?//from   w w  w  .  j a  v a2 s . c  om
 */
public static Map<String, String> getCommentName(final Class clazz) {
    Field[] fields = clazz.getDeclaredFields();
    Map<String, String> map = new HashMap<String, String>();
    for (Field f : fields) {
        Annotation[] aAnnotation = f.getAnnotations();
        for (Annotation annotation : aAnnotation) {
            if (annotation.annotationType() == Comment.class) {
                Comment element = (Comment) annotation;
                map.put(f.getName(), element.value());
            }
        }
    }
    return map;
}

From source file:com.opensymphony.xwork2.util.AnnotationUtils.java

/**
 * Adds all fields with the specified Annotation of class clazz and its superclasses to allFields
 *
 * @param annotationClass the {@link Annotation}s to find
 * @param clazz The {@link Class} to inspect
 * @param allFields list of all fields/*from   w ww .j av  a 2s. c  om*/
 */
public static void addAllFields(Class<? extends Annotation> annotationClass, Class clazz,
        List<Field> allFields) {

    if (clazz == null) {
        return;
    }

    Field[] fields = clazz.getDeclaredFields();

    for (Field field : fields) {
        Annotation ann = field.getAnnotation(annotationClass);
        if (ann != null) {
            allFields.add(field);
        }
    }
    addAllFields(annotationClass, clazz.getSuperclass(), allFields);
}

From source file:com.test.edusys.common.utils.reflection.ReflectionUtils.java

/**
 * //w  ww .ja  v  a 2  s.  c om
 */
public static String getKeyFieldName(final Class clazz) {
    Field[] fields = clazz.getDeclaredFields();
    for (Field f : fields) {
        String filedName = f.getName();
        Annotation[] annotation = f.getAnnotations();
        for (Annotation annotation2 : annotation) {
            Class annotationType = annotation2.annotationType();
            if (annotationType.getName().equals("org.nutz.dao.entity.annotation.Id"))
                return filedName;
            if (annotationType.getName().equals("org.nutz.dao.entity.annotation.Name"))
                return filedName;
        }
    }
    return null;
}

From source file:be.fedict.eid.applet.service.impl.tlv.TlvParser.java

private static <T> T parseThrowing(byte[] file, Class<T> tlvClass) throws InstantiationException,
        IllegalAccessException, DataConvertorException, UnsupportedEncodingException {
    Field[] fields = tlvClass.getDeclaredFields();
    Map<Integer, Field> tlvFields = new HashMap<Integer, Field>();
    for (Field field : fields) {
        TlvField tlvFieldAnnotation = field.getAnnotation(TlvField.class);
        if (null == tlvFieldAnnotation) {
            continue;
        }//from  www.j av  a  2 s . com
        int tagId = tlvFieldAnnotation.value();
        if (tlvFields.containsKey(new Integer(tagId))) {
            throw new IllegalArgumentException("TLV field duplicate: " + tagId);
        }
        tlvFields.put(new Integer(tagId), field);
    }
    T tlvObject = tlvClass.newInstance();

    int idx = 0;
    while (idx < file.length - 1) {
        byte tag = file[idx];
        idx++;
        byte lengthByte = file[idx];
        int length = lengthByte & 0x7f;
        while ((lengthByte & 0x80) == 0x80) {
            idx++;
            lengthByte = file[idx];
            length = (length << 7) + (lengthByte & 0x7f);
        }
        idx++;
        if (0 == tag) {
            idx += length;
            continue;
        }
        if (tlvFields.containsKey(new Integer(tag))) {
            Field tlvField = tlvFields.get(new Integer(tag));
            Class<?> tlvType = tlvField.getType();
            ConvertData convertDataAnnotation = tlvField.getAnnotation(ConvertData.class);
            byte[] tlvValue = copy(file, idx, length);
            Object fieldValue;
            if (null != convertDataAnnotation) {
                Class<? extends DataConvertor<?>> dataConvertorClass = convertDataAnnotation.value();
                DataConvertor<?> dataConvertor = dataConvertorClass.newInstance();
                fieldValue = dataConvertor.convert(tlvValue);
            } else if (String.class == tlvType) {
                fieldValue = new String(tlvValue, "UTF-8");
            } else if (Boolean.TYPE == tlvType) {
                fieldValue = true;
            } else if (tlvType.isArray() && Byte.TYPE == tlvType.getComponentType()) {
                fieldValue = tlvValue;
            } else {
                throw new IllegalArgumentException("unsupported field type: " + tlvType.getName());
            }
            LOG.debug("setting field: " + tlvField.getName());
            if (null != tlvField.get(tlvObject) && false == tlvField.getType().isPrimitive()) {
                throw new RuntimeException("field was already set: " + tlvField.getName());
            }
            tlvField.setAccessible(true);
            tlvField.set(tlvObject, fieldValue);
        } else {
            LOG.debug("unknown tag: " + (tag & 0xff) + ", length: " + length);
        }
        idx += length;
    }
    return tlvObject;
}

From source file:cc.kune.wave.server.CustomSettingsBinder.java

/**
 * Bind configuration parameters into Guice Module.
 *
 * @param propertyFile the property file
 * @param settingsArg the settings arg/* www  .j av  a  2 s .  c o m*/
 * @return a Guice module configured with setting support.
 * @throws ConfigurationException on configuration error
 */
public static Module bindSettings(String propertyFile, Class<?>... settingsArg) throws ConfigurationException {
    final CompositeConfiguration config = new CompositeConfiguration();
    config.addConfiguration(new SystemConfiguration());
    config.addConfiguration(new PropertiesConfiguration(propertyFile));

    List<Field> fields = new ArrayList<Field>();
    for (Class<?> settings : settingsArg) {
        fields.addAll(Arrays.asList(settings.getDeclaredFields()));
    }

    // Reflect on settings class and absorb settings
    final Map<Setting, Field> settings = new LinkedHashMap<Setting, Field>();
    for (Field field : fields) {
        if (!field.isAnnotationPresent(Setting.class)) {
            continue;
        }

        // Validate target type
        SettingTypeValidator typeHelper = supportedSettingTypes.get(field.getType());
        if (typeHelper == null || !typeHelper.check(field.getGenericType())) {
            throw new IllegalArgumentException(field.getType() + " is not one of the supported setting types");
        }

        Setting setting = field.getAnnotation(Setting.class);
        settings.put(setting, field);
    }

    // Now validate them
    List<String> missingProperties = new ArrayList<String>();
    for (Setting setting : settings.keySet()) {
        if (setting.defaultValue().isEmpty()) {
            if (!config.containsKey(setting.name())) {
                missingProperties.add(setting.name());
            }
        }
    }
    if (missingProperties.size() > 0) {
        StringBuilder error = new StringBuilder();
        error.append("The following required properties are missing from the server configuration: ");
        error.append(Joiner.on(", ").join(missingProperties));
        throw new ConfigurationException(error.toString());
    }

    // bundle everything up in an injectable guice module
    return new AbstractModule() {

        @Override
        protected void configure() {
            // We must iterate the settings a third time when binding.
            // Note: do not collapse these loops as that will damage
            // early error detection. The runtime is still O(n) in setting count.
            for (Map.Entry<Setting, Field> entry : settings.entrySet()) {
                Class<?> type = entry.getValue().getType();
                Setting setting = entry.getKey();

                if (int.class.equals(type)) {
                    Integer defaultValue = null;
                    if (!setting.defaultValue().isEmpty()) {
                        defaultValue = Integer.parseInt(setting.defaultValue());
                    }
                    bindConstant().annotatedWith(Names.named(setting.name()))
                            .to(config.getInteger(setting.name(), defaultValue));
                } else if (boolean.class.equals(type)) {
                    Boolean defaultValue = null;
                    if (!setting.defaultValue().isEmpty()) {
                        defaultValue = Boolean.parseBoolean(setting.defaultValue());
                    }
                    bindConstant().annotatedWith(Names.named(setting.name()))
                            .to(config.getBoolean(setting.name(), defaultValue));
                } else if (String.class.equals(type)) {
                    bindConstant().annotatedWith(Names.named(setting.name()))
                            .to(config.getString(setting.name(), setting.defaultValue()));
                } else {
                    String[] value = config.getStringArray(setting.name());
                    if (value.length == 0 && !setting.defaultValue().isEmpty()) {
                        value = setting.defaultValue().split(",");
                    }
                    bind(new TypeLiteral<List<String>>() {
                    }).annotatedWith(Names.named(setting.name())).toInstance(ImmutableList.copyOf(value));
                }
            }
        }
    };
}

From source file:gr.abiss.calipso.uischema.serializer.UiSchemaSerializer.java

private static String getFormFieldConfig(Class domainClass, PropertyDescriptor descriptor, String fieldName) {
    String formSchemaJson = null;
    Field field = null;//from w ww. j a v  a  2s .  c o m
    StringBuffer formConfig = new StringBuffer();
    String key = domainClass.getName() + "#" + fieldName;
    String cached = CONFIG_CACHE.get(key);
    if (StringUtils.isNotBlank(cached)) {
        formConfig.append(cached);
    } else {
        Class tmpClass = domainClass;
        do {
            for (Field tmpField : tmpClass.getDeclaredFields()) {
                String candidateName = tmpField.getName();
                if (candidateName.equals(fieldName)) {
                    field = tmpField;
                    FormSchemas formSchemasAnnotation = null;
                    if (field.isAnnotationPresent(FormSchemas.class)) {
                        formSchemasAnnotation = field.getAnnotation(FormSchemas.class);
                        gr.abiss.calipso.uischema.annotation.FormSchemaEntry[] formSchemas = formSchemasAnnotation
                                .value();
                        LOGGER.info("getFormFieldConfig, formSchemas: " + formSchemas);
                        if (formSchemas != null) {
                            for (int i = 0; i < formSchemas.length; i++) {
                                if (i > 0) {
                                    formConfig.append(comma);
                                }
                                gr.abiss.calipso.uischema.annotation.FormSchemaEntry formSchemaAnnotation = formSchemas[i];
                                LOGGER.info(
                                        "getFormFieldConfig, formSchemaAnnotation: " + formSchemaAnnotation);
                                appendFormFieldSchema(formConfig, formSchemaAnnotation.state(),
                                        formSchemaAnnotation.json());
                            }
                        }
                        //formConfig = formSchemasAnnotation.json();
                    } else {
                        appendFormFieldSchema(formConfig,
                                gr.abiss.calipso.uischema.annotation.FormSchemaEntry.STATE_DEFAULT,
                                gr.abiss.calipso.uischema.annotation.FormSchemaEntry.TYPE_STRING);
                    }
                    break;
                }
            }
            tmpClass = tmpClass.getSuperclass();
        } while (tmpClass != null && field == null);
        formSchemaJson = formConfig.toString();
        CONFIG_CACHE.put(key, formSchemaJson);
    }

    return formSchemaJson;
}

From source file:com.ocs.dynamo.test.MockUtil.java

/**
 * Registers all fields that are annotated with "@Mock" as beans in the Spring context
 * //from w  w w.  j  a  v  a 2s .c o m
 * @param factory
 * @param subject
 * @param clazz
 */
public static void registerMocks(ConfigurableListableBeanFactory factory, Object subject, Class<?> clazz) {
    try {
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            if (field.getAnnotation(Mock.class) != null) {
                factory.registerSingleton(field.getName(), field.get(subject));
            }
        }
        if (clazz.getSuperclass() != null) {
            registerMocks(factory, subject, clazz.getSuperclass());
        }
    } catch (Exception e) {
        throw new OCSRuntimeException(e.getMessage(), e);
    }
}