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:com.ery.ertc.estorm.util.ClassSize.java

/**
 * The estimate of the size of a class instance depends on whether the JVM uses 32 or 64 bit addresses, that is it depends on the size
 * of an object reference. It is a linear function of the size of a reference, e.g. 24 + 5*r where r is the size of a reference (usually
 * 4 or 8 bytes).//from   w w w .jav  a2s.c om
 * 
 * This method returns the coefficients of the linear function, e.g. {24, 5} in the above example.
 * 
 * @param cl
 *            A class whose instance size is to be estimated
 * @param debug
 *            debug flag
 * @return an array of 3 integers. The first integer is the size of the primitives, the second the number of arrays and the third the
 *         number of references.
 */
@SuppressWarnings("unchecked")
private static int[] getSizeCoefficients(Class cl, boolean debug) {
    int primitives = 0;
    int arrays = 0;
    // The number of references that a new object takes
    int references = nrOfRefsPerObj;
    int index = 0;

    for (; null != cl; cl = cl.getSuperclass()) {
        Field[] field = cl.getDeclaredFields();
        if (null != field) {
            for (Field aField : field) {
                if (Modifier.isStatic(aField.getModifiers()))
                    continue;
                Class fieldClass = aField.getType();
                if (fieldClass.isArray()) {
                    arrays++;
                    references++;
                } else if (!fieldClass.isPrimitive()) {
                    references++;
                } else {// Is simple primitive
                    String name = fieldClass.getName();

                    if (name.equals("int") || name.equals("I"))
                        primitives += Bytes.SIZEOF_INT;
                    else if (name.equals("long") || name.equals("J"))
                        primitives += Bytes.SIZEOF_LONG;
                    else if (name.equals("boolean") || name.equals("Z"))
                        primitives += Bytes.SIZEOF_BOOLEAN;
                    else if (name.equals("short") || name.equals("S"))
                        primitives += Bytes.SIZEOF_SHORT;
                    else if (name.equals("byte") || name.equals("B"))
                        primitives += Bytes.SIZEOF_BYTE;
                    else if (name.equals("char") || name.equals("C"))
                        primitives += Bytes.SIZEOF_CHAR;
                    else if (name.equals("float") || name.equals("F"))
                        primitives += Bytes.SIZEOF_FLOAT;
                    else if (name.equals("double") || name.equals("D"))
                        primitives += Bytes.SIZEOF_DOUBLE;
                }
                if (debug) {
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("" + index + " " + aField.getName() + " " + aField.getType());
                    }
                }
                index++;
            }
        }
    }
    return new int[] { primitives, arrays, references };
}

From source file:com.yiji.openapi.sdk.util.Reflections.java

public static Set<String> getSimpleFieldNames(Class<?> pojoClass) {
    Set<String> propertyNames = new HashSet<String>();
    Class<?> clazz = pojoClass;
    do {//from   w  w  w .ja v  a 2 s  .  com
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            if (!Modifier.isStatic(field.getModifiers()) && (field.getType().isPrimitive()
                    || isWrapClass(field.getType()) || field.getType().isAssignableFrom(Timestamp.class)
                    || field.getType().isAssignableFrom(Date.class)
                    || field.getType().isAssignableFrom(String.class)
                    || field.getType().isAssignableFrom(Calendar.class))) {
                propertyNames.add(field.getName());
            }
        }
        clazz = clazz.getSuperclass();
    } while (clazz != null && !clazz.getSimpleName().equalsIgnoreCase("Object"));
    return propertyNames;
}

From source file:org.apache.beam.runners.apex.ApexYarnLauncher.java

private static void copyShallow(DAG from, DAG to) {
    checkArgument(from.getClass() == to.getClass(), "must be same class %s %s", from.getClass(), to.getClass());
    Field[] fields = from.getClass().getDeclaredFields();
    AccessibleObject.setAccessible(fields, true);
    for (int i = 0; i < fields.length; i++) {
        Field field = fields[i];
        if (!java.lang.reflect.Modifier.isStatic(field.getModifiers())) {
            try {
                field.set(to, field.get(from));
            } catch (IllegalArgumentException | IllegalAccessException e) {
                throw new RuntimeException(e);
            }//from w ww  . j a  va 2  s . c o  m
        }
    }
}

From source file:com.example.basedemo.view.ViewInjectorImpl.java

@SuppressWarnings("ConstantConditions")
private static void injectObject(Object handler, Class<?> handlerType, ViewFinder finder) {

    if (handlerType == null || IGNORED.contains(handlerType)) {
        return;/*from  w w  w. j  a  v a 2  s. co m*/
    }

    // ?
    injectObject(handler, handlerType.getSuperclass(), finder);

    // inject view
    Field[] fields = handlerType.getDeclaredFields();
    if (fields != null && fields.length > 0) {
        for (Field field : fields) {

            Class<?> fieldType = field.getType();
            if (
            /* ??? */ Modifier.isStatic(field.getModifiers()) ||
            /* ?final */ Modifier.isFinal(field.getModifiers()) ||
            /* ? */ fieldType.isPrimitive() ||
            /* ? */ fieldType.isArray()) {
                continue;
            }

            ViewInject viewInject = field.getAnnotation(ViewInject.class);
            if (viewInject != null) {
                try {
                    View view = finder.findViewById(viewInject.value(), viewInject.parentId());
                    if (view != null) {
                        field.setAccessible(true);
                        field.set(handler, view);
                    } else {
                        throw new RuntimeException("Invalid @ViewInject for " + handlerType.getSimpleName()
                                + "." + field.getName());
                    }
                } catch (Throwable ex) {
                    Log.e(ex.getMessage(), ex.toString());
                }
            }
        }
    } // end inject view

    // inject event
    Method[] methods = handlerType.getDeclaredMethods();
    if (methods != null && methods.length > 0) {
        for (Method method : methods) {

            if (Modifier.isStatic(method.getModifiers()) || !Modifier.isPrivate(method.getModifiers())) {
                continue;
            }

            //??event
            Event event = method.getAnnotation(Event.class);
            if (event != null) {
                try {
                    // id?
                    int[] values = event.value();
                    int[] parentIds = event.parentId();
                    int parentIdsLen = parentIds == null ? 0 : parentIds.length;
                    //id?ViewInfo???
                    for (int i = 0; i < values.length; i++) {
                        int value = values[i];
                        if (value > 0) {
                            ViewInfo info = new ViewInfo();
                            info.value = value;
                            info.parentId = parentIdsLen > i ? parentIds[i] : 0;
                            method.setAccessible(true);
                            EventListenerManager.addEventMethod(finder, info, event, handler, method);
                        }
                    }
                } catch (Throwable ex) {
                    Log.e(ex.getMessage(), ex.toString());
                }
            }
        }
    } // end inject event

}

From source file:com.asuka.android.asukaandroid.view.ViewInjectorImpl.java

@SuppressWarnings("ConstantConditions")
private static void injectObject(Object handler, Class<?> handlerType, ViewFinder finder) {

    if (handlerType == null || IGNORED.contains(handlerType)) {
        return;//from w  w w.  ja  v a2  s.  co  m
    }

    // ?
    injectObject(handler, handlerType.getSuperclass(), finder);

    // inject view
    Field[] fields = handlerType.getDeclaredFields();
    if (fields != null && fields.length > 0) {
        for (Field field : fields) {

            Class<?> fieldType = field.getType();
            if (
            /* ??? */ Modifier.isStatic(field.getModifiers()) ||
            /* ?final */ Modifier.isFinal(field.getModifiers()) ||
            /* ? */ fieldType.isPrimitive() ||
            /* ? */ fieldType.isArray()) {
                continue;
            }

            ViewInject viewInject = field.getAnnotation(ViewInject.class);
            if (viewInject != null) {
                try {
                    View view = finder.findViewById(viewInject.value(), viewInject.parentId());
                    if (view != null) {
                        field.setAccessible(true);
                        field.set(handler, view);
                    } else {
                        throw new RuntimeException("Invalid @ViewInject for " + handlerType.getSimpleName()
                                + "." + field.getName());
                    }
                } catch (Throwable ex) {
                    LogUtil.e(ex.getMessage(), ex);
                }
            }
        }
    } // end inject view

    // inject event
    Method[] methods = handlerType.getDeclaredMethods();
    if (methods != null && methods.length > 0) {
        for (Method method : methods) {

            if (Modifier.isStatic(method.getModifiers()) || !Modifier.isPrivate(method.getModifiers())) {
                continue;
            }

            //??event
            Event event = method.getAnnotation(Event.class);
            if (event != null) {
                try {
                    // id?
                    int[] values = event.value();
                    int[] parentIds = event.parentId();
                    int parentIdsLen = parentIds == null ? 0 : parentIds.length;
                    //id?ViewInfo???
                    for (int i = 0; i < values.length; i++) {
                        int value = values[i];
                        if (value > 0) {
                            ViewInfo info = new ViewInfo();
                            info.value = value;
                            info.parentId = parentIdsLen > i ? parentIds[i] : 0;
                            method.setAccessible(true);
                            EventListenerManager.addEventMethod(finder, info, event, handler, method);
                        }
                    }
                } catch (Throwable ex) {
                    LogUtil.e(ex.getMessage(), ex);
                }
            }
        }
    } // end inject event

}

From source file:org.alfresco.module.org_alfresco_module_rm.api.PublicAPITestUtil.java

/**
 * Get all the classes referenced by the given class, which might be used by an extension. We consider visible
 * methods, constructors, fields and inner classes, as well as superclasses and interfaces extended by the class.
 *
 * @param initialClass The class to analyse.
 * @param consideredClasses Classes that have already been considered, and which should not be considered again. If
 *            the given class has already been considered then an empty set will be returned. This set will be
 *            updated with the given class.
 * @return The set of classes that might be accessible by an extension of this class.
 *///  ww w.  j  a  va2 s  .c o  m
private static Set<Class<?>> getReferencedClassesFromClass(Class<?> initialClass,
        Set<Class<?>> consideredClasses) {
    Set<Class<?>> referencedClasses = new HashSet<>();

    if (consideredClasses.add(initialClass)) {
        for (Method method : initialClass.getDeclaredMethods()) {
            if (isVisibleToExtender(method.getModifiers())) {
                referencedClasses.addAll(getClassesFromMethod(method));
            }
        }
        for (Constructor<?> constructor : initialClass.getDeclaredConstructors()) {
            if (isVisibleToExtender(constructor.getModifiers())) {
                referencedClasses.addAll(getClassesFromConstructor(constructor));
            }
        }
        for (Field field : initialClass.getDeclaredFields()) {
            if (isVisibleToExtender(field.getModifiers())) {
                referencedClasses.addAll(getClassesFromField(field));
            }
        }
        for (Class<?> clazz : initialClass.getDeclaredClasses()) {
            if (isVisibleToExtender(clazz.getModifiers())) {
                referencedClasses.addAll(getReferencedClassesFromClass(clazz, consideredClasses));
            }
        }
        if (initialClass.getSuperclass() != null) {
            referencedClasses
                    .addAll(getReferencedClassesFromClass(initialClass.getSuperclass(), consideredClasses));
        }
        for (Class<?> clazz : initialClass.getInterfaces()) {
            referencedClasses.addAll(getReferencedClassesFromClass(clazz, consideredClasses));
        }
    }
    return referencedClasses;
}

From source file:org.apache.abdera.util.AbderaConfiguration.java

private static String getName(Class<? extends StreamWriter> sw) {
    String name = null;/*from w  w  w.  j  a va2 s . co  m*/
    try {
        Field field = sw.getField("NAME");
        if (Modifier.isStatic(field.getModifiers())) {
            name = (String) field.get(null);
        }
    } catch (Exception e) {
    }
    return name;
}

From source file:edu.illinois.ncsa.springdata.SpringData.java

/**
 * Check each field in object to see if it is already seen. This will modify
 * collections, lists and arrays as well as the fields in an object.
 * /*from w ww.jav a  2  s  .c  om*/
 * @param obj
 *            the object to be checked for duplicates.
 * @param seen
 *            objects that have already been checked.
 * @return the object with all duplicates removed
 */
private static <T> T removeDuplicate(T obj, Map<String, Object> seen) {
    if (obj == null) {
        return null;
    }
    if (obj instanceof AbstractBean) {
        String id = ((AbstractBean) obj).getId();
        if (seen.containsKey(id)) {
            return (T) seen.get(id);
        }
        seen.put(id, obj);

        // check all subfields
        for (Field field : obj.getClass().getDeclaredFields()) {
            if ((field.getModifiers() & Modifier.FINAL) == 0) {
                try {
                    field.setAccessible(true);
                    field.set(obj, removeDuplicate(field.get(obj), seen));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

    } else if (obj instanceof Collection<?>) {
        Collection col = (Collection) obj;
        ArrayList arr = new ArrayList(col);
        col.clear();
        for (int i = 0; i < arr.size(); i++) {
            Object x = removeDuplicate(arr.get(i), seen);
            col.add(x);
        }
    } else if (obj instanceof Map<?, ?>) {
        Map map = (Map) obj;
        ArrayList<Entry> arr = new ArrayList(map.entrySet());
        map.clear();
        for (int i = 0; i < arr.size(); i++) {
            Object k = removeDuplicate(arr.get(i).getKey(), seen);
            Object v = removeDuplicate(arr.get(i).getValue(), seen);
            map.put(k, v);
        }
    } else if (obj.getClass().isArray()) {
        Object[] arr = (Object[]) obj;
        for (int i = 0; i < arr.length; i++) {
            arr[i] = removeDuplicate(arr[i], seen);
        }
    }

    return obj;
}

From source file:org.apache.syncope.core.persistence.jpa.entity.JPAAnyUtils.java

private static void initFieldNames(final Class<?> entityClass, final Set<String> keys) {
    List<Class<?>> classes = ClassUtils.getAllSuperclasses(entityClass);
    classes.add(entityClass);//from ww  w  . ja  v  a 2  s.  co m
    for (Class<?> clazz : classes) {
        for (Field field : clazz.getDeclaredFields()) {
            if (!Modifier.isStatic(field.getModifiers()) && !field.getName().startsWith("pc")
                    && !Collection.class.isAssignableFrom(field.getType())
                    && !Map.class.isAssignableFrom(field.getType())) {

                keys.add("id".equals(field.getName()) ? "key" : field.getName());
            }
        }
    }
}

From source file:io.github.benas.randombeans.util.ReflectionUtils.java

/**
 * Check if a field is static./*from   ww w  . j ava 2s  .  c  o  m*/
 *
 * @param field the field to check
 * @return true if the field is static, false otherwise
 */
public static boolean isStatic(final Field field) {
    return Modifier.isStatic(field.getModifiers());
}