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:ml.shifu.shifu.container.meta.MetaFactory.java

/**
 * Iterate each property of Object, get the value and validate
 * /*from  ww  w. ja va  2s.co m*/
 * @param isGridSearch
 *            - if grid search, ignore validation in train#params as they are set all as list
 * @param ptag
 *            - the prefix of key to search @MetaItem
 * @param obj
 *            - the object to validate
 * @return ValidateResult
 *         If all items are OK, the ValidateResult.status will be true;
 *         Or the ValidateResult.status will be false, ValidateResult.causes will contain the reasons
 * @throws Exception
 *             any exception in validaiton
 */
public static ValidateResult iterateCheck(boolean isGridSearch, String ptag, Object obj) throws Exception {
    ValidateResult result = new ValidateResult(true);
    if (obj == null) {
        return result;
    }

    Class<?> cls = obj.getClass();
    Field[] fields = cls.getDeclaredFields();

    Class<?> parentCls = cls.getSuperclass();
    if (!parentCls.equals(Object.class)) {
        Field[] pfs = parentCls.getDeclaredFields();
        fields = (Field[]) ArrayUtils.addAll(fields, pfs);
    }

    for (Field field : fields) {
        if (!field.isSynthetic() && !Modifier.isStatic(field.getModifiers()) && !isJsonIngoreField(field)) {
            Method method = cls.getMethod("get" + getMethodName(field.getName()));
            Object value = method.invoke(obj);

            encapsulateResult(result,
                    validate(isGridSearch, ptag + ITEM_KEY_SEPERATOR + field.getName(), value));
        }
    }

    return result;
}

From source file:com.comphenix.noxp.FieldUtils.java

/**
 * Gets an accessible <code>Field</code> by name breaking scope if
 * requested. Superclasses/interfaces will be considered.
 * /*w w  w . j a  v  a 2  s  .  c o m*/
 * @param cls the class to reflect, must not be null
 * @param fieldName the field name to obtain
 * @param forceAccess whether to break scope restrictions using the
 *            <code>setAccessible</code> method. <code>False</code> will
 *            only match public fields.
 * @return the Field object
 * @throws IllegalArgumentException if the class or field name is null
 */
public static Field getField(final Class cls, String fieldName, boolean forceAccess) {
    if (cls == null) {
        throw new IllegalArgumentException("The class must not be null");
    }
    if (fieldName == null) {
        throw new IllegalArgumentException("The field name must not be null");
    }
    // Sun Java 1.3 has a bugged implementation of getField hence we write
    // the
    // code ourselves

    // getField() will return the Field object with the declaring class
    // set correctly to the class that declares the field. Thus requesting
    // the
    // field on a subclass will return the field from the superclass.
    //
    // priority order for lookup:
    // searchclass private/protected/package/public
    // superclass protected/package/public
    // private/different package blocks access to further superclasses
    // implementedinterface public

    // check up the superclass hierarchy
    for (Class acls = cls; acls != null; acls = acls.getSuperclass()) {
        try {
            Field field = acls.getDeclaredField(fieldName);
            // getDeclaredField checks for non-public scopes as well
            // and it returns accurate results
            if (!Modifier.isPublic(field.getModifiers())) {
                if (forceAccess) {
                    field.setAccessible(true);
                } else {
                    continue;
                }
            }
            return field;
        } catch (NoSuchFieldException ex) {
            // ignore
        }
    }
    // check the public interface case. This must be manually searched for
    // incase there is a public supersuperclass field hidden by a
    // private/package
    // superclass field.
    Field match = null;
    for (Iterator intf = ClassUtils.getAllInterfaces(cls).iterator(); intf.hasNext();) {
        try {
            Field test = ((Class) intf.next()).getField(fieldName);
            if (match != null) {
                throw new IllegalArgumentException(
                        "Reference to field " + fieldName + " is ambiguous relative to " + cls
                                + "; a matching field exists on two or more implemented interfaces.");
            }
            match = test;
        } catch (NoSuchFieldException ex) {
            // ignore
        }
    }
    return match;
}

From source file:com.jk.util.JKObjectUtil.java

/**
 * Checks if is final./* ww w  .j  a  v a  2 s.com*/
 *
 * @param field
 *            the field
 * @return true, if is final
 */
public static boolean isFinal(final Field field) {
    return Modifier.isFinal(field.getModifiers());
}

From source file:com.jk.util.JKObjectUtil.java

/**
 * Checks if is transient./*from  w  w w  .ja v a 2s.  com*/
 *
 * @param field
 *            the field
 * @return true, if is transient
 */
public static boolean isTransient(final Field field) {
    return Modifier.isTransient(field.getModifiers());
}

From source file:com.pmarlen.model.controller.EntityJPAToPlainPojoTransformer.java

public static void copyPlainValues(Entity entity, Object plain) {
    final Class entityClass;
    entityClass = entity.getClass();//from   w w w  . j a  v a2  s.c  o  m
    final String entityClassName = entityClass.getName();
    Hashtable<String, Object> propertiesToCopy = new Hashtable<String, Object>();
    Hashtable<String, Object> propertiesM2MToCopy = new Hashtable<String, Object>();
    List<String> propertiesWithNULLValueToCopy = new ArrayList<String>();
    List<String> propertiesKey = new ArrayList<String>();
    try {
        final Field[] declaredFields = entityClass.getDeclaredFields();
        for (Field f : declaredFields) {
            logger.trace("->create: \tcopy: " + entityClassName + "." + f.getName() + " accesible ? "
                    + (f.isAccessible()));
            if (!f.isAccessible()) {

                if (f.isAnnotationPresent(javax.persistence.Id.class)) {
                    propertiesKey.add(f.getName());
                }
                if (f.isAnnotationPresent(javax.persistence.Id.class)
                        && !f.isAnnotationPresent(javax.persistence.GeneratedValue.class)
                        && !Modifier.isStatic(f.getModifiers())) {

                    Object valueCopyed = PropertyUtils.getProperty(entity, f.getName());
                    if (valueCopyed != null) {
                        propertiesToCopy.put(f.getName(), valueCopyed);
                    } else {
                        propertiesWithNULLValueToCopy.add(f.getName());
                    }
                    logger.trace("->create:\t\t ID elegible 2 be copied, added to copy list: " + f.getName()
                            + " = " + valueCopyed + ", is really null?" + (valueCopyed == null));
                } else if (!f.isAnnotationPresent(javax.persistence.Id.class)
                        && !f.isAnnotationPresent(javax.persistence.OneToMany.class)
                        && !f.isAnnotationPresent(javax.persistence.ManyToMany.class)
                        && !Modifier.isStatic(f.getModifiers())) {

                    Object valueCopyed = PropertyUtils.getProperty(entity, f.getName());
                    if (valueCopyed != null) {
                        propertiesToCopy.put(f.getName(), valueCopyed);
                    } else {
                        propertiesWithNULLValueToCopy.add(f.getName());
                    }
                    logger.trace("->create:\t\t elegible 2 be copied, added to copy list: " + f.getName()
                            + " = " + valueCopyed + ", is really null?" + (valueCopyed == null));
                } else if (!f.isAnnotationPresent(javax.persistence.Id.class)
                        && f.isAnnotationPresent(javax.persistence.ManyToMany.class)) {

                    Object valueCopyed = PropertyUtils.getProperty(entity, f.getName());
                    if (valueCopyed != null) {
                        propertiesM2MToCopy.put(f.getName(), valueCopyed);
                    } else {
                        propertiesWithNULLValueToCopy.add(f.getName());
                    }
                    logger.trace("->create:\t\t M2M elegible 2 be copied, added to copy list: " + f.getName()
                            + " = " + valueCopyed + ", is really null?" + (valueCopyed == null));
                }
            }
        }
        logger.trace("->create:copy values ?");
        for (String p2c : propertiesToCopy.keySet()) {
            Object valueCopyed = propertiesToCopy.get(p2c);
            logger.trace("->create:\t\t copy value with SpringUtils: " + p2c + " = " + valueCopyed
                    + ", is null?" + (valueCopyed == null));
            BeanUtils.copyProperty(plain, p2c, valueCopyed);
        }
        for (String p2c : propertiesWithNULLValueToCopy) {
            logger.trace("->create:\t\t copy null with SpringUtils");
            BeanUtils.copyProperty(plain, p2c, null);
        }
    } catch (Exception e) {
        logger.error("..in copy", e);
    }
}

From source file:br.com.lucasisrael.regra.reflections.TratamentoReflections.java

/**
 * Make the given field accessible, explicitly setting it accessible if
 * necessary. The {@code setAccessible(true)} method is only called
 * when actually necessary, to avoid unnecessary conflicts with a JVM
 * SecurityManager (if active).// ww w.j  ava 2 s .c  o m
 * @param field the field to make accessible
 * @see java.lang.reflect.Field#setAccessible
 */
public static void makeAccessible(Field field) {
    if ((!Modifier.isPublic(field.getModifiers())
            || !Modifier.isPublic(field.getDeclaringClass().getModifiers())
            || Modifier.isFinal(field.getModifiers())) && !field.isAccessible()) {
        field.setAccessible(true);
    }
}

From source file:com.android.camera2.its.ItsSerializer.java

@SuppressWarnings("unchecked")
public static JSONObject serialize(CameraMetadata md) throws ItsException {
    JSONObject jsonObj = new JSONObject();
    Field[] allFields = md.getClass().getDeclaredFields();
    if (md.getClass() == TotalCaptureResult.class) {
        allFields = CaptureResult.class.getDeclaredFields();
    }/*from   ww w.ja v  a2 s.  co  m*/
    for (Field field : allFields) {
        if (Modifier.isPublic(field.getModifiers()) && Modifier.isStatic(field.getModifiers())
                && (field.getType() == CaptureRequest.Key.class || field.getType() == CaptureResult.Key.class
                        || field.getType() == TotalCaptureResult.Key.class
                        || field.getType() == CameraCharacteristics.Key.class)
                && field.getGenericType() instanceof ParameterizedType) {
            ParameterizedType paramType = (ParameterizedType) field.getGenericType();
            Type[] argTypes = paramType.getActualTypeArguments();
            if (argTypes.length > 0) {
                try {
                    Type keyType = argTypes[0];
                    Object keyObj = field.get(md);
                    MetadataEntry entry;
                    if (keyType instanceof GenericArrayType) {
                        entry = serializeArrayEntry(keyType, keyObj, md);
                    } else {
                        entry = serializeEntry(keyType, keyObj, md);
                    }

                    // TODO: Figure this weird case out.
                    // There is a weird case where the entry is non-null but the toString
                    // of the entry is null, and if this happens, the null-ness spreads like
                    // a virus and makes the whole JSON object null from the top level down.
                    // Not sure if it's a bug in the library or I'm just not using it right.
                    // Workaround by checking for this case explicitly and not adding the
                    // value to the jsonObj when it is detected.
                    if (entry != null && entry.key != null && entry.value != null
                            && entry.value.toString() == null) {
                        Logt.w(TAG, "Error encountered serializing value for key: " + entry.key);
                    } else if (entry != null) {
                        jsonObj.put(entry.key, entry.value);
                    } else {
                        // Ignore.
                    }
                } catch (IllegalAccessException e) {
                    throw new ItsException("Access error for field: " + field + ": ", e);
                } catch (org.json.JSONException e) {
                    throw new ItsException("JSON error for field: " + field + ": ", e);
                }
            }
        }
    }
    return jsonObj;
}

From source file:ch.flashcard.HibernateDetachUtility.java

private static void nullOutFieldsByFieldAccess(Object object, Map<Integer, Object> checkedObjects,
        Map<Integer, List<Object>> checkedObjectCollisionMap, int depth, SerializationType serializationType)
        throws Exception {

    Class tmpClass = object.getClass();
    List<Field> fieldsToClean = new ArrayList<Field>();
    while (tmpClass != null && tmpClass != Object.class) {
        Field[] declaredFields = tmpClass.getDeclaredFields();
        for (Field declaredField : declaredFields) {
            // do not process static final or transient fields since they won't be serialized anyway
            int modifiers = declaredField.getModifiers();
            if (!((Modifier.isFinal(modifiers) && Modifier.isStatic(modifiers))
                    || Modifier.isTransient(modifiers))) {
                fieldsToClean.add(declaredField);
            }/*from   w w w.ja v  a 2  s. com*/
        }
        tmpClass = tmpClass.getSuperclass();
    }

    nullOutFieldsByFieldAccess(object, fieldsToClean, checkedObjects, checkedObjectCollisionMap, depth,
            serializationType);
}

From source file:com.taobao.weex.wson.Wson.java

private static final List<Field> getBeanFields(String key, Class targetClass) {
    List<Field> fieldList = fieldsCache.get(key);
    if (fieldList == null) {
        Field[] fields = targetClass.getFields();
        fieldList = new ArrayList<>(fields.length);
        for (Field field : fields) {
            if ((field.getModifiers() & Modifier.STATIC) != 0) {
                continue;
            }// w  ww.ja va 2s . c  om
            if (field.getAnnotation(JSONField.class) != null) {
                throw new UnsupportedOperationException(
                        "getBeanMethod JSONField Annotation Not Handled, Use toJSON");
            }
            fieldList.add(field);
        }
        fieldsCache.put(key, fieldList);
    }
    return fieldList;
}

From source file:com.opengamma.financial.analytics.ircurve.CurveSpecificationBuilderConfiguration.java

private static List<String> getCurveSpecBuilderConfigurationNames() {
    final List<String> list = new ArrayList<>();
    for (final Field field : CurveSpecificationBuilderConfigurationFudgeBuilder.class.getDeclaredFields()) {
        if (Modifier.isStatic(field.getModifiers()) && field.isSynthetic() == false) {
            field.setAccessible(true);/*from w  w  w . ja v  a 2s. com*/
            try {
                list.add((String) field.get(null));
            } catch (final Exception ex) {
                // Ignore
            }
        }
    }
    Collections.sort(list, String.CASE_INSENSITIVE_ORDER);
    return ImmutableList.copyOf(list);
}