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:org.openmrs.module.distrotools.test.TestUtils.java

/**
 * Modifies a constant in a constants class. If the constant is final and not based on a runtime expression, then
 * it's value will have been inlined by the compiler and this method will have no effect.
 * @param constantsClass the class of constants
 * @param fieldName the field name of the constant
 * @param newValue the new value for the constant
 * @throws Exception if field not found or couldn't be modified
 *//*from  ww  w .  ja v  a  2 s .  co m*/
public static void modifyConstant(Class<?> constantsClass, String fieldName, Object newValue) throws Exception {
    Field field = constantsClass.getDeclaredField(fieldName);
    field.setAccessible(true);

    int existingModifiers = field.getModifiers();

    // Remove final modifier from field
    Field modifiersField = Field.class.getDeclaredField("modifiers");
    modifiersField.setAccessible(true);
    modifiersField.setInt(field, existingModifiers & ~Modifier.FINAL);

    field.set(null, newValue);

    // Reset previous modifiers
    modifiersField.setInt(field, existingModifiers);
}

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

private static void initFieldNames(final Class<?> entityClass, final Set<String> keys) {
    List<Class<?>> classes = ClassUtils.getAllSuperclasses(entityClass);
    classes.add(entityClass);/*from w w w  .ja v  a2 s.co m*/
    for (Class<?> clazz : classes) {
        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:cn.org.awcp.core.mybatis.mapper.EntityHelper.java

/**
 * ?Field/*from w  w w  .j av a 2  s  .  c om*/
 * 
 * @param entityClass
 * @param fieldList
 * @return
 */
private static List<Field> getAllField(Class<?> entityClass, List<Field> fieldList) {
    if (fieldList == null) {
        fieldList = new ArrayList<Field>();
    }
    if (entityClass.equals(Object.class)) {
        return fieldList;
    }
    Field[] fields = entityClass.getDeclaredFields();
    for (Field field : fields) {
        // ??bug#2
        if (!Modifier.isStatic(field.getModifiers())) {
            fieldList.add(field);
        }
    }
    if (entityClass.getSuperclass() != null && !entityClass.getSuperclass().equals(Object.class)
            && !Map.class.isAssignableFrom(entityClass.getSuperclass())
            && !Collection.class.isAssignableFrom(entityClass.getSuperclass())) {
        return getAllField(entityClass.getSuperclass(), fieldList);
    }
    return fieldList;
}

From source file:net.radai.beanz.util.ReflectionUtil.java

public static Field findField(Class<?> clazz, String propName) {
    Class<?> c = clazz;//from   w  ww. j ava 2 s.  c o m
    while (c != null) {
        for (Field f : c.getDeclaredFields()) {
            if (!f.getName().equals(propName)) {
                continue;
            }
            int modifiers = f.getModifiers();
            if (Modifier.isStatic(modifiers)) {
                continue;
            }
            return f;
        }
        c = c.getSuperclass();
    }
    return null;
}

From source file:com.dungnv.vfw5.base.utils.StringUtils.java

public static void escapeHTMLString(Object escapeObject) {
    String oldData = "";
    String newData = "";
    try {/*w  w  w  .  j a v a  2 s  .c  o  m*/
        if (escapeObject != null) {
            Class escapeClass = escapeObject.getClass();
            Field fields[] = escapeClass.getDeclaredFields();
            Field superFields[] = escapeClass.getSuperclass().getDeclaredFields();
            Field allField[] = new Field[fields.length + superFields.length];
            System.arraycopy(fields, 0, allField, 0, fields.length);
            System.arraycopy(superFields, 0, allField, fields.length, superFields.length);
            for (Field f : allField) {
                f.setAccessible(true);
                if (f.getType().equals(java.lang.String.class) && !Modifier.isFinal(f.getModifiers())) {
                    if (f.get(escapeObject) != null) {
                        oldData = f.get(escapeObject).toString();
                        newData = StringEscapeUtils.escapeSql(oldData);
                        f.set(escapeObject, newData);
                    }
                } else if (f.getType().isArray()) {
                    if (f.getType().getComponentType().equals(java.lang.String.class)) {
                        String[] tmpArr = (String[]) f.get(escapeObject);
                        if (tmpArr != null) {
                            for (int i = 0; i < tmpArr.length; i++) {
                                tmpArr[i] = StringEscapeUtils.escapeSql(tmpArr[i]);
                            }
                            f.set(escapeObject, tmpArr);
                        }
                    }
                } else if (f.get(escapeObject) instanceof List) {
                    List<Object> tmpList = (List<Object>) f.get(escapeObject);
                    for (int i = 0; i < tmpList.size(); i++) {
                        if (tmpList.get(i) instanceof java.lang.String) {
                            tmpList.set(i, StringEscapeUtils.escapeSql(tmpList.get(i).toString()));
                        }
                    }
                    f.set(escapeObject, tmpList);
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.dungnv.vfw5.base.utils.StringUtils.java

public static void trimString(Object obj, boolean isLower) {
    String oldData = "";
    String newData = "";
    try {/* www .j a  v a2  s . c o m*/
        if (obj != null) {
            Class escapeClass = obj.getClass();
            Field fields[] = escapeClass.getDeclaredFields();
            Field superFields[] = escapeClass.getSuperclass().getDeclaredFields();
            Field allField[] = new Field[fields.length + superFields.length];
            System.arraycopy(fields, 0, allField, 0, fields.length);
            System.arraycopy(superFields, 0, allField, fields.length, superFields.length);
            for (Field f : allField) {
                f.setAccessible(true);
                if (f.getType().equals(java.lang.String.class) && !Modifier.isFinal(f.getModifiers())) {
                    if (f.get(obj) != null) {
                        oldData = f.get(obj).toString();
                        newData = isLower ? oldData.trim().toLowerCase() : oldData.trim();
                        f.set(obj, newData);
                    }
                } else if (f.getType().isArray()) {
                    if (f.getType().getComponentType().equals(java.lang.String.class)) {
                        String[] tmpArr = (String[]) f.get(obj);
                        if (tmpArr != null) {
                            for (int i = 0; i < tmpArr.length; i++) {
                                tmpArr[i] = isLower ? tmpArr[i].trim().toLowerCase() : tmpArr[i].trim();
                            }
                            f.set(obj, tmpArr);
                        }
                    }
                } else if (f.get(obj) instanceof List) {
                    List<Object> tmpList = (List<Object>) f.get(obj);
                    for (int i = 0; i < tmpList.size(); i++) {
                        if (tmpList.get(i) instanceof java.lang.String) {
                            tmpList.set(i, isLower ? tmpList.get(i).toString().trim().toLowerCase()
                                    : tmpList.get(i).toString().trim());
                        }
                    }
                    f.set(obj, tmpList);
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:HashCodeBuilder.java

/**
 * This method uses reflection to build a valid hash code. 
 * <p>//from  www  .ja  v  a 2  s  . co m
 * It uses Field.setAccessible to gain access to private fields. This means
 * that it will throw a security exception if run under a security manger, if
 * the permissions are not set up.
 * It is also not as efficient as testing explicitly. 
 * If the TestTransients parameter is set to true, transient members will be
 * tested, otherwise they are ignored, as they are likely derived fields, and
 * not part of the value of the object. 
 * Static fields will not be tested.
 * <p>
 * Two randomly chosen, non-zero, odd numbers must be passed in. Ideally
 * these should be different for each class, however this is not vital.
 * Prime numbers are preferred, especially for the multiplier.
 * 
 * @param initialNonZeroOddNumber
 * @param multiplierNonZeroOddNumber
 * @param object  the object to create a hash code for
 * @param testTransients  whether to include transient fields
 * @return int hash code
 * @throws IllegalArgumentException if the object is null
 * @throws IllegalArgumentException if the number is zero or even
 */
public static int reflectionHashCode(int initialNonZeroOddNumber, int multiplierNonZeroOddNumber, Object object,
        boolean testTransients) {

    if (object == null) {
        throw new IllegalArgumentException("The object to build a hash code for must not be null");
    }
    HashCodeBuilder hashCodeBuilder = new HashCodeBuilder(initialNonZeroOddNumber, multiplierNonZeroOddNumber);
    Field[] fields = object.getClass().getDeclaredFields();
    Field.setAccessible(fields, true);
    for (int i = 0; i < fields.length; ++i) {
        Field f = fields[i];
        if (testTransients || !Modifier.isTransient(f.getModifiers())) {
            if (!Modifier.isStatic(f.getModifiers())) {
                try {
                    hashCodeBuilder.append(f.get(object));
                } 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");
                }
            }
        }
    }
    return hashCodeBuilder.toHashCode();
}

From source file:com.autobizlogic.abl.util.BeanUtil.java

private static Field getFieldFromClass(Class<?> cls, String fieldName, Class<?> argClass,
        boolean onlyProtectedAndHigher) {
    Field[] allFields = cls.getDeclaredFields();
    for (Field field : allFields) {
        if (!field.getName().equals(fieldName))
            continue;
        int modifiers = field.getModifiers();
        if (onlyProtectedAndHigher && Modifier.isPrivate(modifiers))
            continue;
        if (argClass != null) {
            Class<?> genericType = getGenericType(field.getType());
            if (!genericType.isAssignableFrom(argClass)) {
                String extraInfo = "";
                // If the two classes have the same name, it's probably a classloader problem,
                // so we generate more informative output to help debug
                if (field.getType().getName().equals(argClass.getName())) {
                    extraInfo = ". It looks like the two classes have the same name, so this is "
                            + "probably a classloader issue. The bean field's class comes from "
                            + field.getType().getClassLoader() + ", the other class comes from "
                            + argClass.getClassLoader();
                }/*w  w  w.ja  v a2s.  c o m*/
                throw new RuntimeException("Bean field " + fieldName + " of class " + cls.getName()
                        + " is of the wrong type (" + field.getType().getName() + ") for the given argument, "
                        + "which is of type " + argClass.getName() + extraInfo);
            }
        }

        return field;
    }

    return null;
}

From source file:com.bosscs.spark.commons.utils.Utils.java

/**
 * Returns an instance clone.//from  w  w  w  .j  a  v a2  s  . c  o m
 * this method gets every class property by reflection, including its parents properties
 * @param t
 * @param <T>
 * @return T object.
 */
public static <T> T cloneObjectWithParents(T t) throws IllegalAccessException, InstantiationException {
    T clone = (T) t.getClass().newInstance();

    List<Field> allFields = new ArrayList<>();

    Class parentClass = t.getClass().getSuperclass();

    while (parentClass != null) {
        Collections.addAll(allFields, parentClass.getDeclaredFields());
        parentClass = parentClass.getSuperclass();
    }

    Collections.addAll(allFields, t.getClass().getDeclaredFields());

    for (Field field : allFields) {
        int modifiers = field.getModifiers();
        //We skip final and static fields
        if ((Modifier.FINAL & modifiers) != 0 || (Modifier.STATIC & modifiers) != 0) {
            continue;
        }
        field.setAccessible(true);

        Object value = field.get(t);

        if (Collection.class.isAssignableFrom(field.getType())) {
            Collection collection = (Collection) field.get(clone);
            if (collection == null) {
                collection = (Collection) field.get(t).getClass().newInstance();
            }
            collection.addAll((Collection) field.get(t));
            value = collection;
        } else if (Map.class.isAssignableFrom(field.getType())) {
            Map clonMap = (Map) field.get(t).getClass().newInstance();
            clonMap.putAll((Map) field.get(t));
            value = clonMap;
        }
        field.set(clone, value);
    }

    return clone;
}

From source file:com.twinsoft.convertigo.beans.CheckBeans.java

private static void analyzeJavaClass(String javaClassName) {
    try {/*  w w w . j  a va2 s .c o m*/
        Class<?> javaClass = Class.forName(javaClassName);
        String javaClassSimpleName = javaClass.getSimpleName();

        if (!DatabaseObject.class.isAssignableFrom(javaClass)) {
            //Error.NON_DATABASE_OBJECT.add(javaClassName);
            return;
        }

        nBeanClass++;

        String dboBeanInfoClassName = javaClassName + "BeanInfo";
        MySimpleBeanInfo dboBeanInfo = null;
        try {
            dboBeanInfo = (MySimpleBeanInfo) (Class.forName(dboBeanInfoClassName)).newInstance();
        } catch (ClassNotFoundException e) {
            if (!Modifier.isAbstract(javaClass.getModifiers())) {
                Error.MISSING_BEAN_INFO
                        .add(javaClassName + " (expected bean info: " + dboBeanInfoClassName + ")");
            }
            return;
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }

        BeanDescriptor beanDescriptor = dboBeanInfo.getBeanDescriptor();

        // Check abstract class
        if (Modifier.isAbstract(javaClass.getModifiers())) {
            // Check icon (16x16)
            String declaredIconName = MySimpleBeanInfo.getIconName(dboBeanInfo,
                    MySimpleBeanInfo.ICON_COLOR_16x16);
            if (declaredIconName != null) {
                Error.ABSTRACT_CLASS_WITH_ICON.add(javaClassName);
            }

            // Check icon (32x32)
            declaredIconName = MySimpleBeanInfo.getIconName(dboBeanInfo, MySimpleBeanInfo.ICON_COLOR_32x32);
            if (declaredIconName != null) {
                Error.ABSTRACT_CLASS_WITH_ICON.add(javaClassName);
            }

            // Check display name
            if (!beanDescriptor.getDisplayName().equals("?")) {
                Error.ABSTRACT_CLASS_WITH_DISPLAY_NAME.add(javaClassName);
            }

            // Check description
            if (!beanDescriptor.getShortDescription().equals("?")) {
                Error.ABSTRACT_CLASS_WITH_DESCRIPTION.add(javaClassName);
            }
        } else {
            nBeanClassNotAbstract++;

            // Check bean declaration in database_objects.xml
            if (!dboXmlDeclaredDatabaseObjects.contains(javaClassName)) {
                Error.BEAN_DEFINED_BUT_NOT_USED.add(javaClassName);
            }

            // Check icon name policy (16x16)
            String declaredIconName = MySimpleBeanInfo.getIconName(dboBeanInfo,
                    MySimpleBeanInfo.ICON_COLOR_16x16);
            String expectedIconName = javaClassName.replace(javaClassSimpleName,
                    "images/" + javaClassSimpleName);
            expectedIconName = "/" + expectedIconName.replace('.', '/') + "_color_16x16";
            expectedIconName = expectedIconName.toLowerCase() + ".png";
            if (declaredIconName != null) {
                if (!declaredIconName.equals(expectedIconName)) {
                    Error.BEAN_ICON_NAMING_POLICY.add(javaClassName + "\n" + "      Declared: "
                            + declaredIconName + "\n" + "      Expected: " + expectedIconName);
                }
            }

            // Check icon file (16x16)
            File iconFile = new File(srcBase + declaredIconName);
            if (!iconFile.exists()) {
                Error.BEAN_MISSING_ICON.add(javaClassName + " - icon missing: " + declaredIconName);
            } else {
                icons.remove(declaredIconName);
            }

            // Check icon name policy (32x32)
            declaredIconName = MySimpleBeanInfo.getIconName(dboBeanInfo, MySimpleBeanInfo.ICON_COLOR_32x32);
            expectedIconName = javaClassName.replace(javaClassSimpleName, "images/" + javaClassSimpleName);
            expectedIconName = "/" + expectedIconName.replace('.', '/') + "_color_32x32";
            expectedIconName = expectedIconName.toLowerCase() + ".png";
            if (declaredIconName != null) {
                if (!declaredIconName.equals(expectedIconName)) {
                    Error.BEAN_ICON_NAMING_POLICY.add(javaClassName + "\n" + "      Declared: "
                            + declaredIconName + "\n" + "      Expected: " + expectedIconName);
                }
            }

            // Check icon file (32x32)
            iconFile = new File(srcBase + declaredIconName);
            if (!iconFile.exists()) {
                Error.BEAN_MISSING_ICON.add(javaClassName + " - icon missing: " + declaredIconName);
            } else {
                icons.remove(declaredIconName);
            }

            // Check display name
            if (beanDescriptor.getDisplayName().equals("?")) {
                Error.BEAN_MISSING_DISPLAY_NAME.add(javaClassName);
            }

            // Check description
            if (beanDescriptor.getShortDescription().equals("?")) {
                Error.BEAN_MISSING_DESCRIPTION.add(javaClassName);
            }
        }

        // Check declared bean properties
        PropertyDescriptor[] propertyDescriptors = dboBeanInfo.getLocalPropertyDescriptors();
        for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
            String propertyName = propertyDescriptor.getName();
            try {
                javaClass.getDeclaredField(propertyName);
            } catch (SecurityException e) {
                e.printStackTrace();
            } catch (NoSuchFieldException e) {
                try {
                    // Try to find it in the upper classes
                    javaClass.getField(propertyName);
                } catch (SecurityException e1) {
                    // printStackTrace();
                } catch (NoSuchFieldException e1) {
                    Error.PROPERTY_DECLARED_BUT_NOT_FOUND.add(javaClassName + ": " + propertyName);
                }
            }
        }

        Method[] methods = javaClass.getDeclaredMethods();
        List<Method> listMethods = Arrays.asList(methods);
        List<String> listMethodNames = new ArrayList<String>();
        for (Method method : listMethods) {
            listMethodNames.add(method.getName());
        }

        Field[] fields = javaClass.getDeclaredFields();

        for (Field field : fields) {
            int fieldModifiers = field.getModifiers();

            // Ignore static fields (constants)
            if (Modifier.isStatic(fieldModifiers))
                continue;

            String fieldName = field.getName();

            String errorMessage = javaClassName + ": " + field.getName();

            // Check bean info
            PropertyDescriptor propertyDescriptor = isBeanProperty(fieldName, dboBeanInfo);
            if (propertyDescriptor != null) {
                // Check bean property name policy
                if (!propertyDescriptor.getName().equals(fieldName)) {
                    Error.PROPERTY_NAMING_POLICY.add(errorMessage);
                }

                String declaredGetter = propertyDescriptor.getReadMethod().getName();
                String declaredSetter = propertyDescriptor.getWriteMethod().getName();

                String formattedFieldName = Character.toUpperCase(fieldName.charAt(0)) + fieldName.substring(1);
                String expectedGetter = "get" + formattedFieldName;
                String expectedSetter = "set" + formattedFieldName;

                // Check getter name policy
                if (!declaredGetter.equals(expectedGetter)) {
                    Error.GETTER_SETTER_DECLARED_EXPECTED_NAMES_MISMATCH
                            .add(errorMessage + "\n" + "      Declared getter: " + declaredGetter + "\n"
                                    + "      Expected getter: " + expectedGetter);
                }

                // Check setter name policy
                if (!declaredSetter.equals(expectedSetter)) {
                    Error.GETTER_SETTER_DECLARED_EXPECTED_NAMES_MISMATCH
                            .add(errorMessage + "\n" + "      Declared setter: " + declaredSetter + "\n"
                                    + "      Expected setter: " + expectedSetter);
                }

                // Check required private modifiers for bean property
                if (!Modifier.isPrivate(fieldModifiers)) {
                    Error.PROPERTY_NOT_PRIVATE.add(errorMessage);
                }

                // Check getter
                if (!listMethodNames.contains(declaredGetter)) {
                    Error.GETTER_SETTER_DECLARED_BUT_NOT_FOUND
                            .add(errorMessage + " - Declared getter not found: " + declaredGetter);
                }

                // Check setter
                if (!listMethodNames.contains(declaredSetter)) {
                    Error.GETTER_SETTER_DECLARED_BUT_NOT_FOUND
                            .add(errorMessage + " - Declared setter not found: " + declaredGetter);
                }

                // Check non transient modifier
                if (Modifier.isTransient(fieldModifiers)) {
                    Error.PROPERTY_TRANSIENT.add(errorMessage);
                }
            } else if (!Modifier.isTransient(fieldModifiers)) {
                Error.FIELD_NOT_TRANSIENT.add(errorMessage);
            }
        }
    } catch (ClassNotFoundException e) {
        System.out.println("ERROR on " + javaClassName);
        e.printStackTrace();
    }
}