Example usage for java.lang.reflect Field getModifiers

List of usage examples for java.lang.reflect Field getModifiers

Introduction

In this page you can find the example usage for java.lang.reflect Field getModifiers.

Prototype

public int getModifiers() 

Source Link

Document

Returns the Java language modifiers for the field represented by this Field object, as an integer.

Usage

From source file:edu.usu.sdl.openstorefront.doc.EntityProcessor.java

private static void addFields(Class entity, EntityDocModel docModel) {
    if (entity != null) {
        Field[] fields = entity.getDeclaredFields();
        for (Field field : fields) {
            //Skip static field
            if ((Modifier.isStatic(field.getModifiers()) && Modifier.isFinal(field.getModifiers())) == false) {

                EntityFieldModel fieldModel = new EntityFieldModel();
                fieldModel.setName(field.getName());
                fieldModel.setType(field.getType().getSimpleName());
                fieldModel.setOriginClass(entity.getSimpleName());
                fieldModel.setEmbeddedType(ReflectionUtil.isComplexClass(field.getType()));
                if (ReflectionUtil.isCollectionClass(field.getType())) {
                    DataType dataType = (DataType) field.getAnnotation(DataType.class);
                    if (dataType != null) {
                        String typeClass = dataType.value().getSimpleName();
                        if (StringUtils.isNotBlank(dataType.actualClassName())) {
                            typeClass = dataType.actualClassName();
                        }//w  ww .java 2s. co m
                        fieldModel.setGenericType(typeClass);
                    }
                }

                APIDescription description = (APIDescription) field.getAnnotation(APIDescription.class);
                if (description != null) {
                    fieldModel.setDescription(description.value());
                }

                for (Annotation annotation : field.getAnnotations()) {
                    if (annotation.annotationType().getName().equals(APIDescription.class.getName()) == false) {
                        EntityConstraintModel entityConstraintModel = new EntityConstraintModel();
                        entityConstraintModel.setName(annotation.annotationType().getSimpleName());

                        APIDescription annotationDescription = (APIDescription) annotation.annotationType()
                                .getAnnotation(APIDescription.class);
                        if (annotationDescription != null) {
                            entityConstraintModel.setDescription(annotationDescription.value());
                        }

                        //rules
                        Object annObj = field.getAnnotation(annotation.annotationType());
                        if (annObj instanceof NotNull) {
                            entityConstraintModel.setRules("Field is required");
                        } else if (annObj instanceof PK) {
                            PK pk = (PK) annObj;
                            entityConstraintModel.setRules("<b>Generated:</b> " + pk.generated());
                            fieldModel.setPrimaryKey(true);
                        } else if (annObj instanceof FK) {
                            FK fk = (FK) annObj;

                            StringBuilder sb = new StringBuilder();
                            sb.append("<b>Foreign Key:</b> ").append(fk.value().getSimpleName());
                            sb.append(" (<b>Enforce</b>: ").append(fk.enforce());
                            sb.append(" <b>Soft reference</b>: ").append(fk.softReference());
                            if (StringUtils.isNotBlank(fk.referencedField())) {
                                sb.append(" <b>Reference Field</b>: ").append(fk.referencedField());
                            }
                            sb.append(" )");
                            entityConstraintModel.setRules(sb.toString());
                        } else if (annObj instanceof ConsumeField) {
                            entityConstraintModel.setRules("");
                        } else if (annObj instanceof Size) {
                            Size size = (Size) annObj;
                            entityConstraintModel
                                    .setRules("<b>Min:</b> " + size.min() + " <b>Max:</b> " + size.max());
                        } else if (annObj instanceof Pattern) {
                            Pattern pattern = (Pattern) annObj;
                            entityConstraintModel.setRules("<b>Pattern:</b> " + pattern.regexp());
                        } else if (annObj instanceof Sanitize) {
                            Sanitize sanitize = (Sanitize) annObj;
                            entityConstraintModel
                                    .setRules("<b>Sanitize:</b> " + sanitize.value().getSimpleName());
                        } else if (annObj instanceof Unique) {
                            Unique unique = (Unique) annObj;
                            entityConstraintModel.setRules("<b>Handler:</b> " + unique.value().getSimpleName());
                        } else if (annObj instanceof ValidValueType) {
                            ValidValueType validValueType = (ValidValueType) annObj;
                            StringBuilder sb = new StringBuilder();
                            if (validValueType.value().length > 0) {
                                sb.append(" <b>Values:</b> ").append(Arrays.toString(validValueType.value()));
                            }

                            if (validValueType.lookupClass().length > 0) {
                                sb.append(" <b>Lookups:</b> ");
                                for (Class lookupClass : validValueType.lookupClass()) {
                                    sb.append(lookupClass.getSimpleName()).append("  ");
                                }
                            }

                            if (validValueType.enumClass().length > 0) {
                                sb.append(" <b>Enumerations:</b> ");
                                for (Class enumClass : validValueType.enumClass()) {
                                    sb.append(enumClass.getSimpleName()).append("  (");
                                    sb.append(Arrays.toString(enumClass.getEnumConstants())).append(")");
                                }
                            }

                            entityConstraintModel.setRules(sb.toString());
                        } else if (annObj instanceof Min) {
                            Min min = (Min) annObj;
                            entityConstraintModel.setRules("<b>Min value:</b> " + min.value());
                        } else if (annObj instanceof Max) {
                            Max max = (Max) annObj;
                            entityConstraintModel.setRules("<b>Max value:</b> " + max.value());
                        } else if (annObj instanceof Version) {
                            entityConstraintModel.setRules("Entity version; For Multi-Version control");
                        } else if (annObj instanceof DataType) {
                            DataType dataType = (DataType) annObj;
                            String typeClass = dataType.value().getSimpleName();
                            if (StringUtils.isNotBlank(dataType.actualClassName())) {
                                typeClass = dataType.actualClassName();
                            }
                            entityConstraintModel.setRules("<b>Type:</b> " + typeClass);
                        } else {
                            entityConstraintModel.setRules(annotation.toString());
                        }

                        //Annotations that have related classes
                        if (annObj instanceof DataType) {
                            DataType dataType = (DataType) annObj;
                            entityConstraintModel.getRelatedClasses().add(dataType.value().getSimpleName());
                        }
                        if (annObj instanceof FK) {
                            FK fk = (FK) annObj;
                            entityConstraintModel.getRelatedClasses().add(fk.value().getSimpleName());
                        }
                        if (annObj instanceof ValidValueType) {
                            ValidValueType validValueType = (ValidValueType) annObj;
                            for (Class lookupClass : validValueType.lookupClass()) {
                                entityConstraintModel.getRelatedClasses().add(lookupClass.getSimpleName());
                            }

                            StringBuilder sb = new StringBuilder();
                            for (Class enumClass : validValueType.enumClass()) {
                                sb.append("<br>");
                                sb.append(enumClass.getSimpleName()).append(":  (");
                                sb.append(Arrays.toString(enumClass.getEnumConstants())).append(")");
                            }
                            entityConstraintModel
                                    .setRules(entityConstraintModel.getRules() + " " + sb.toString());
                        }

                        fieldModel.getConstraints().add(entityConstraintModel);
                    }
                }

                docModel.getFieldModels().add(fieldModel);
            }
        }
        addFields(entity.getSuperclass(), docModel);
    }
}

From source file:com.qrmedia.commons.persistence.hibernate.clone.HibernateEntityBeanCloner.java

private static Collection<String> calculateTargetedFieldNames(Object entity, boolean preserveIdFields) {
    Collection<String> targetedFieldNames = new ArrayList<String>();
    Class<?> entityClass = entity.getClass();

    for (Field field : ClassUtils.getAllDeclaredFields(entityClass)) {
        String fieldName = field.getName();

        // ignore static members and members without a valid getter and setter
        if (!Modifier.isStatic(field.getModifiers()) && PropertyUtils.isReadable(entity, fieldName)
                && PropertyUtils.isWriteable(entity, fieldName)) {
            targetedFieldNames.add(field.getName());
        }//from w w  w .j  a  v a2  s.  co m

    }

    /*
     * Assume that, in accordance with recommendations, entities are using *either* JPA property
     * *or* field access. Guess the access type from the location of the @Id annotation, as
     * Hibernate does.
     */
    Set<Method> idAnnotatedMethods = ClassUtils.getAnnotatedMethods(entityClass, Id.class);
    boolean usingFieldAccess = idAnnotatedMethods.isEmpty();

    // ignore fields annotated with @Version and, optionally, @Id
    targetedFieldNames.removeAll(usingFieldAccess
            ? getFieldNames(ClassUtils.getAllAnnotatedDeclaredFields(entityClass, Version.class))
            : getPropertyNames(ClassUtils.getAnnotatedMethods(entityClass, Version.class)));

    if (!preserveIdFields) {
        targetedFieldNames.removeAll(usingFieldAccess
                ? getFieldNames(ClassUtils.getAllAnnotatedDeclaredFields(entityClass, Id.class))
                : getPropertyNames(idAnnotatedMethods));
    }

    return targetedFieldNames;
}

From source file:microsoft.exchange.webservices.data.core.service.schema.ServiceObjectSchema.java

/**
 * Adds schema property to dictionary./*from  ww w.j av  a  2  s.  c  o  m*/
 *
 * @param type              Schema type.
 * @param propDefDictionary The property definition dictionary.
 */
protected static void addSchemaPropertiesToDictionary(Class<?> type,
        Map<String, PropertyDefinitionBase> propDefDictionary) {
    Field[] fields = type.getDeclaredFields();
    for (Field field : fields) {
        int modifier = field.getModifiers();
        if (Modifier.isPublic(modifier) && Modifier.isStatic(modifier)) {
            Object o;
            try {
                o = field.get(null);
                if (o instanceof PropertyDefinition) {
                    PropertyDefinition propertyDefinition = (PropertyDefinition) o;
                    // Some property definitions descend from
                    // ServiceObjectPropertyDefinition but don't have
                    // a Uri, like ExtendedProperties. Ignore them.
                    if (null != propertyDefinition.getUri() && !propertyDefinition.getUri().isEmpty()) {
                        PropertyDefinitionBase existingPropertyDefinition;
                        if (propDefDictionary.containsKey(propertyDefinition.getUri())) {
                            existingPropertyDefinition = propDefDictionary.get(propertyDefinition.getUri());
                            EwsUtilities.ewsAssert(existingPropertyDefinition == propertyDefinition,
                                    "Schema.allSchemaProperties." + "delegate",
                                    String.format(
                                            "There are at least " + "two distinct property "
                                                    + "definitions with the" + " following URI: %s",
                                            propertyDefinition.getUri()));
                        } else {
                            propDefDictionary.put(propertyDefinition.getUri(), propertyDefinition);
                            // The following is a "generic hack" to register
                            // property that are not public and
                            // thus not returned by the above GetFields
                            // call. It is currently solely used to register
                            // the MeetingTimeZone property.
                            List<PropertyDefinition> associatedInternalProperties = propertyDefinition
                                    .getAssociatedInternalProperties();
                            for (PropertyDefinition associatedInternalProperty : associatedInternalProperties) {
                                propDefDictionary.put(associatedInternalProperty.getUri(),
                                        associatedInternalProperty);
                            }

                        }
                    }
                }
            } catch (IllegalArgumentException e) {
                LOG.error(e);

                // Skip the field
            } catch (IllegalAccessException e) {
                LOG.error(e);

                // Skip the field
            }

        }
    }
}

From source file:org.apache.cassandra.config.Config.java

public static void log(Config config) {
    Map<String, String> configMap = new TreeMap<>();
    for (Field field : Config.class.getFields()) {
        // ignore the constants
        if (Modifier.isFinal(field.getModifiers()))
            continue;

        String name = field.getName();
        if (SENSITIVE_KEYS.contains(name)) {
            configMap.put(name, "<REDACTED>");
            continue;
        }/*from   ww w.  ja va2s .  com*/

        String value;
        try {
            // Field.get() can throw NPE if the value of the field is null
            value = field.get(config).toString();
        } catch (NullPointerException | IllegalAccessException npe) {
            value = "null";
        }
        configMap.put(name, value);
    }

    logger.info("Node configuration:[" + Joiner.on("; ").join(configMap.entrySet()) + "]");
}

From source file:org.apache.syncope.client.console.wizards.AbstractMappingPanel.java

private static void initFieldNames(final Class<?> entityClass, final Set<String> keys) {
    List<Class<?>> classes = ClassUtils.getAllSuperclasses(entityClass);
    classes.add(entityClass);/*w  w w .  j  a  v a2 s .c om*/
    classes.forEach(clazz -> {
        for (Field field : clazz.getDeclaredFields()) {
            if (!Modifier.isStatic(field.getModifiers()) && !Collection.class.isAssignableFrom(field.getType())
                    && !Map.class.isAssignableFrom(field.getType())) {

                keys.add(field.getName());
            }
        }
    });
}

From source file:com.coinblesk.client.utils.ClientUtils.java

private static void setFinalStatic(Field field, Object newValue) throws Exception {
    field.setAccessible(true);/* www  .  jav a2s  . com*/

    // remove final modifier from field
    try {
        Field modifiersField = Field.class.getDeclaredField("modifiers");
        modifiersField.setAccessible(true);
        modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
    } catch (Exception e) {
        Log.w(TAG, "Could not remove 'final' modifier: " + e.getMessage());
    }
    field.set(null, newValue);
}

From source file:edu.usu.sdl.openstorefront.util.ReflectionUtil.java

/**
 * This gets all declared field of the whole object hierarchy
 *
 * @param typeClass//from   w w w  .  j a  v  a  2s .  co  m
 * @return
 */
public static List<Field> getAllFields(Class typeClass) {
    Objects.requireNonNull(typeClass, "Class is required");

    List<Field> fields = new ArrayList<>();
    if (typeClass.getSuperclass() != null) {
        fields.addAll(getAllFields(typeClass.getSuperclass()));
    }
    for (Field field : typeClass.getDeclaredFields()) {
        if (Modifier.isStatic(field.getModifiers()) == false
                && Modifier.isFinal(field.getModifiers()) == false) {
            fields.add(field);
        }
    }
    return fields;
}

From source file:ReflectUtil.java

/**
 * Looks for an instance (i.e. non-static) public field with the matching name and
 * returns it if one exists.  If no such field exists, returns null.
 *
 * @param clazz the clazz who's fields to examine
 * @param property the name of the property/field to look for
 * @return the Field object or null if no matching field exists
 *//* w w  w.jav  a 2 s  . c om*/
public static Field getField(Class<?> clazz, String property) {
    try {
        Field field = clazz.getField(property);
        return !Modifier.isStatic(field.getModifiers()) ? field : null;
    } catch (NoSuchFieldException nsfe) {
        return null;
    }
}

From source file:de.tuberlin.uebb.jbop.access.ClassAccessor.java

/**
 * Tests whether the given field of input is final.
 * //  w  w  w.  j a v a2s  .c om
 * @param input
 *          the object
 * @param fieldName
 *          the field name
 * @return true, if is final
 */
public static boolean isFinal(final Object input, final String fieldName) {
    final Field declaredField = getField(input, fieldName);
    if (declaredField == null) {
        return false;
    }
    return (declaredField.getModifiers() & Modifier.FINAL) != 0;
}

From source file:net.minecraftforge.common.config.ConfigManager.java

private static void sync(Configuration cfg, Class<?> cls, String modid, String category, boolean loading,
        Object instance) {//w w w . j  a v a 2 s.c o m
    for (Field f : cls.getDeclaredFields()) {
        if (!Modifier.isPublic(f.getModifiers()))
            continue;

        //Only the root class may have static fields. Otherwise category tree nodes of the same type would share the
        //contained value messing up the sync
        if (Modifier.isStatic(f.getModifiers()) != (instance == null))
            continue;

        if (f.isAnnotationPresent(Config.Ignore.class))
            continue;

        String comment = null;
        Comment ca = f.getAnnotation(Comment.class);
        if (ca != null)
            comment = NEW_LINE.join(ca.value());

        String langKey = modid + "." + (category.isEmpty() ? "" : category + Configuration.CATEGORY_SPLITTER)
                + f.getName().toLowerCase(Locale.ENGLISH);
        LangKey la = f.getAnnotation(LangKey.class);
        if (la != null)
            langKey = la.value();

        boolean requiresMcRestart = f.isAnnotationPresent(Config.RequiresMcRestart.class);
        boolean requiresWorldRestart = f.isAnnotationPresent(Config.RequiresWorldRestart.class);

        if (FieldWrapper.hasWrapperFor(f)) //Wrappers exist for primitives, enums, maps and arrays
        {
            if (Strings.isNullOrEmpty(category))
                throw new RuntimeException(
                        "An empty category may not contain anything but objects representing categories!");
            try {
                IFieldWrapper wrapper = FieldWrapper.get(instance, f, category);
                ITypeAdapter adapt = wrapper.getTypeAdapter();
                Property.Type propType = adapt.getType();

                for (String key : wrapper.getKeys()) //Iterate the fully qualified property names the field provides
                {
                    String suffix = StringUtils.replaceOnce(key,
                            wrapper.getCategory() + Configuration.CATEGORY_SPLITTER, "");

                    boolean existed = exists(cfg, wrapper.getCategory(), suffix);
                    if (!existed || loading) //Creates keys in category specified by the wrapper if new ones are programaticaly added
                    {
                        Property property = property(cfg, wrapper.getCategory(), suffix, propType,
                                adapt.isArrayAdapter());

                        adapt.setDefaultValue(property, wrapper.getValue(key));
                        if (!existed)
                            adapt.setValue(property, wrapper.getValue(key));
                        else
                            wrapper.setValue(key, adapt.getValue(property));
                    } else //If the key is not new, sync according to shouldReadFromVar()
                    {
                        Property property = property(cfg, wrapper.getCategory(), suffix, propType,
                                adapt.isArrayAdapter());
                        Object propVal = adapt.getValue(property);
                        Object mapVal = wrapper.getValue(key);
                        if (shouldReadFromVar(property, propVal, mapVal))
                            adapt.setValue(property, mapVal);
                        else
                            wrapper.setValue(key, propVal);
                    }
                }

                ConfigCategory confCat = cfg.getCategory(wrapper.getCategory());

                for (Property property : confCat.getOrderedValues()) //Iterate the properties to check for new data from the config side
                {
                    String key = confCat.getQualifiedName() + Configuration.CATEGORY_SPLITTER
                            + property.getName();
                    if (!wrapper.handlesKey(key))
                        continue;

                    if (loading || !wrapper.hasKey(key)) {
                        Object value = wrapper.getTypeAdapter().getValue(property);
                        wrapper.setValue(key, value);
                    }
                }

                if (loading)
                    wrapper.setupConfiguration(cfg, comment, langKey, requiresMcRestart, requiresWorldRestart);

            } catch (Exception e) {
                String format = "Error syncing field '%s' of class '%s'!";
                String error = String.format(format, f.getName(), cls.getName());
                throw new RuntimeException(error, e);
            }
        } else if (f.getType().getSuperclass() != null && f.getType().getSuperclass().equals(Object.class)) { //If the field extends Object directly, descend the object tree and access the objects members
            Object newInstance = null;
            try {
                newInstance = f.get(instance);
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            }

            //Setup the sub category with its respective name, comment, language key, etc.
            String sub = (category.isEmpty() ? "" : category + Configuration.CATEGORY_SPLITTER)
                    + getName(f).toLowerCase(Locale.ENGLISH);
            ConfigCategory confCat = cfg.getCategory(sub);
            confCat.setComment(comment);
            confCat.setLanguageKey(langKey);
            confCat.setRequiresMcRestart(requiresMcRestart);
            confCat.setRequiresWorldRestart(requiresWorldRestart);

            sync(cfg, f.getType(), modid, sub, loading, newInstance);
        } else {
            String format = "Can't handle field '%s' of class '%s': Unknown type.";
            String error = String.format(format, f.getName(), cls.getCanonicalName());
            throw new RuntimeException(error);
        }
    }
}