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:de.terrestris.shogun.dao.DatabaseDao.java

/**
 * TODO move to a better place or use existing functionality elsewhere.
 * TODO we have a very similar method in {@link HibernateFilterItem}.
 *
 * @param fields/*from w w w.  java 2 s .  co m*/
 * @param type
 * @return
 * @throws NoSuchFieldException
 * @throws SecurityException
 * @throws IntrospectionException
 */
public static List<Field> getAllFields(List<Field> fields, Class<?> type) {
    for (Field field : type.getDeclaredFields()) {

        // check if the filed is not a constant
        if (Modifier.isStatic(field.getModifiers()) == false
                && Modifier.isFinal(field.getModifiers()) == false) {

            // now we check if the readmethod of the field
            // has NOT a transient annotation
            try {
                PropertyDescriptor pd = new PropertyDescriptor(field.getName(), type);
                Method readmethod = pd.getReadMethod();
                Annotation[] annotationsArr = readmethod.getAnnotations();
                if (annotationsArr.length == 0) {
                    fields.add(field);
                } else {
                    for (Annotation annotation : annotationsArr) {
                        if (annotation.annotationType().equals(javax.persistence.Transient.class) == false) {
                            fields.add(field);
                        }
                    }
                }
            } catch (IntrospectionException e) {
                LOGGER.error("Trying to determine the getter for field '" + field.getName() + "' in "
                        + type.getSimpleName() + " threw IntrospectionException."
                        + " Is there a getter following the Java-Beans" + " Specification?");
            }
        }

    }

    if (type.getSuperclass() != null) {
        fields = getAllFields(fields, type.getSuperclass());
    }

    return fields;
}

From source file:com.google.ratel.util.RatelUtils.java

private static Object createDeepInstance(Class type, Set<Class> cyclicDetector) {
    cyclicDetector.add(type);//from   ww  w.  ja  v a2  s. c o  m
    //System.out.println("Depth: " + callingDepth);

    try {
        Object obj = null;

        // Handle primitives
        if (defaultValues.containsKey(type)) {
            Object defaultValue = defaultValues.get(type);
            obj = defaultValue;

            // Handle Arrays
        } else if (type.isArray()) {
            Class arrayType = type.getComponentType();

            // Check cyclic dependency
            if (!cyclicDetector.contains(arrayType)) {

                Set<Class> localCyclicDetector = new HashSet<Class>(cyclicDetector);
                Object value = createDeepInstance(arrayType, localCyclicDetector);
                obj = Array.newInstance(arrayType, 1);
                Array.set(obj, 0, value);
            }

        } else {
            // Handle pojo
            obj = type.newInstance();

            List<Field> fullFieldList = getAllFields(type);

            for (Field field : fullFieldList) {
                Class fieldType = field.getType();

                // Check for cyclic dependency
                if (!cyclicDetector.contains(fieldType)) {
                    Set<Class> localCyclicDetector = new HashSet<Class>(cyclicDetector);
                    Object fieldObj = createDeepInstance(fieldType, localCyclicDetector);
                    if (!Modifier.isPublic(field.getModifiers())) {
                        field.setAccessible(true);
                    }

                    field.set(obj, fieldObj);

                    if (!Modifier.isPublic(field.getModifiers())) {
                        field.setAccessible(false);
                    }
                }

            }
        }
        return obj;

    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:ru.gkpromtech.exhibition.db.Table.java

protected Table(Class<T> entityClass, SQLiteOpenHelper sqlHelper) throws InvalidPropertiesFormatException {

    mEntityClass = entityClass;//w  w  w  . j  av  a 2 s. co m
    mSqlHelper = sqlHelper;

    TableRef tableRef = entityClass.getAnnotation(TableRef.class);
    mTableName = tableRef.name();
    //        mTr = tableRef.tr();

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

    for (Field field : mEntityClass.getFields())
        if (!Modifier.isStatic(field.getModifiers()))
            fields.add(field);

    List<FkInfo> fks = new ArrayList<>();
    mFields = fields.toArray(new Field[fields.size()]);
    mColumns = new String[mFields.length];
    mType = new int[mFields.length];
    for (int i = 0; i < mFields.length; ++i) {
        Field field = mFields[i];

        mColumns[i] = field.getName();
        switch (field.getType().getSimpleName()) {
        case "int":
        case "Integer":
            mType[i] = INTEGER;
            break;
        case "Short":
        case "short":
            mType[i] = SHORT;
            break;
        case "long":
        case "Long":
            mType[i] = LONG;
            break;

        case "float":
        case "Float":
            mType[i] = FLOAT;
            break;

        case "double":
        case "Double":
            mType[i] = DOUBLE;
            break;

        case "String":
            mType[i] = STRING;
            break;

        case "byte[]":
            mType[i] = BYTE_ARRAY;
            break;

        case "Date":
            mType[i] = DATE;
            break;

        case "boolean":
            mType[i] = BOOLEAN;
            break;

        default:
            throw new InvalidPropertiesFormatException(
                    "Unsupported type: " + field.getType().getCanonicalName());
        }

        FK fk = field.getAnnotation(FK.class);
        if (fk != null)
            fks.add(new FkInfo(fk.entity(), fk.field(), field.getName()));
    }

    mFks = fks.toArray(new FkInfo[fks.size()]);
}

From source file:com.fluidops.iwb.api.ProviderServiceImpl.java

protected void collectUserObjects(Object config, List<User> users) throws IOException {
    if (config == null)
        return;//from   w  ww.j  ava  2  s  .co m

    if (config instanceof User)
        users.add((User) config);

    for (Field f : config.getClass().getFields()) {
        if (Modifier.isTransient(f.getModifiers()))
            continue;
        if (Modifier.isStatic(f.getModifiers()))
            continue;

        try {
            Object kid = f.get(config);
            if (kid instanceof Object[])
                for (Object item : (Object[]) kid)
                    collectUserObjects(item, users);
            else if (kid instanceof Collection)
                for (Object item : (Collection) kid)
                    collectUserObjects(item, users);
            else
                collectUserObjects(kid, users);
        } catch (Exception e) {
            throw new IOException(
                    "Error saving config object. Could not check for User data. Make sure config objects are simple pojos with public fields",
                    e);
        }
    }
}

From source file:org.hfoss.posit.android.sync.Communicator.java

/**
 * Returns a list on name/value pairs for the Find.  Should work for Plugin Finds as
 * well as Basic Finds.  //from w w w.j  a  v a2s  .  co  m
 * @param find
 * @param clazz
 * @return
 */
private static List<NameValuePair> getNameValuePairs(Find find, Class clazz) {
    Field[] fields = clazz.getDeclaredFields();

    List<NameValuePair> nvp = new ArrayList<NameValuePair>();
    String methodName = "";
    String value = "";

    for (Field field : fields) {
        //         Log.i(TAG, "class= " + clazz + " field = " + field);
        if (!Modifier.isFinal(field.getModifiers())) {
            String key = field.getName();
            methodName = "get" + key.substring(0, 1).toUpperCase() + key.substring(1);
            value = "";

            try {
                Class returnType = clazz.getDeclaredMethod(methodName, null).getReturnType();
                if (returnType.equals(String.class))
                    value = (String) clazz.getDeclaredMethod(methodName, null).invoke(find, (Object[]) null);
                else if (returnType.equals(int.class))
                    value = String.valueOf(
                            (Integer) clazz.getDeclaredMethod(methodName, null).invoke(find, (Object[]) null));
                else if (returnType.equals(double.class))
                    value = String.valueOf(
                            (Double) clazz.getDeclaredMethod(methodName, null).invoke(find, (Object[]) null));
                else if (returnType.equals(boolean.class))
                    value = String.valueOf(
                            (Boolean) clazz.getDeclaredMethod(methodName, null).invoke(find, (Object[]) null));

            } catch (IllegalArgumentException e) {
                Log.e(TAG, e + ": " + e.getMessage());
            } catch (SecurityException e) {
                Log.e(TAG, e + ": " + e.getMessage());
            } catch (IllegalAccessException e) {
                Log.e(TAG, e + ": " + e.getMessage());
            } catch (InvocationTargetException e) {
                Log.e(TAG, e + ": " + e.getMessage());
            } catch (NoSuchMethodException e) {
                Log.e(TAG, e + ": " + e.getMessage());
            }
            nvp.add(new BasicNameValuePair(key, value));
        }
    }
    return nvp;

}

From source file:org.apache.openaz.xacml.std.json.JSONResponse.java

/**
 * Use reflection to load the map with all the names of all DataTypes allowing us to output the shorthand
 * version rather than the full Identifier name. (to shorten the JSON output). The shorthand map is used
 * differently in JSONRequest than in JSONResponse, so there are similarities and differences in the
 * implementation. This is done once the first time a Request is processed.
 *///from   www. j a v a  2 s . co  m
private static void initOutputShorthandMap() throws JSONStructureException {
    Field[] declaredFields = XACML3.class.getDeclaredFields();
    outputShorthandMap = new HashMap<String, String>();
    for (Field field : declaredFields) {
        if (Modifier.isStatic(field.getModifiers()) && field.getName().startsWith("ID_DATATYPE")
                && Modifier.isPublic(field.getModifiers())) {
            try {
                Identifier id = (Identifier) field.get(null);
                String longName = id.stringValue();
                // most names start with 'http://www.w3.org/2001/XMLSchema#'
                int sharpIndex = longName.lastIndexOf("#");
                if (sharpIndex <= 0) {
                    // some names start with 'urn:oasis:names:tc:xacml:1.0:data-type:'
                    // or urn:oasis:names:tc:xacml:2.0:data-type:
                    if (longName.contains(":data-type:")) {
                        sharpIndex = longName.lastIndexOf(":");
                    } else {
                        continue;
                    }
                }
                String shortName = longName.substring(sharpIndex + 1);
                // put both the full name and the short name in the table
                outputShorthandMap.put(id.stringValue(), shortName);
            } catch (Exception e) {
                throw new JSONStructureException("Error loading ID Table, e=" + e);
            }
        }
    }
}

From source file:name.yumaa.ChromeLogger4J.java

/**
 * Converts an object to a better format for logging
 * @param object    variable to conver//from  ww  w. j  a  v  a 2s . c  o  m
 * @param depth     recursion depth
 * @return converted object, ready to put to JSON
 */
private Object convert(Object object, int depth) {
    // *** return simple types as is ***
    if (object == null || object instanceof String || object instanceof Number || object instanceof Boolean)
        return object;

    // *** other simple types ***

    if (object instanceof Character || object instanceof StringBuffer || object instanceof StringBuilder
            || object instanceof Currency || object instanceof Date || object instanceof Locale)
        return object.toString();

    if (object instanceof Calendar)
        return ((Calendar) object).getTime().toString();

    if (object instanceof SimpleDateFormat)
        return ((SimpleDateFormat) object).toPattern();

    // check recursion depth
    if (depth > this.depth)
        return "d>" + this.depth;

    // mark this object as processed so we don't convert it twice and it
    // also avoid recursion when objects refer to each other
    processed.add(object);

    // *** not so simple types, but we can foreach it ***

    if (object instanceof Map) {
        JSONObject jobject = new JSONObject();
        for (Object key : ((Map<Object, Object>) object).keySet()) {
            Object value = ((Map<Object, Object>) object).get(key);
            addValue(jobject, key.toString(), value, depth);
        }
        return jobject;
    }

    if (object instanceof Collection) {
        JSONArray jobject = new JSONArray();
        for (Object value : (Collection<Object>) object)
            addValue(jobject, value, depth);
        return jobject;
    }

    if (object instanceof Iterable) {
        JSONArray jobject = new JSONArray();
        for (Object value : (Iterable<Object>) object)
            addValue(jobject, value, depth);
        return jobject;
    }

    if (object instanceof Object[]) {
        JSONArray jobject = new JSONArray();
        for (Object value : (Object[]) object)
            addValue(jobject, value, depth);
        return jobject;
    }

    // *** object of unknown type ***

    JSONObject jobject = new JSONObject();

    Class<?> cls = object.getClass();
    jobject.put("___class_name", cls.getName()); // add the class name
    jobject.put("___toString()", object.toString()); // and to string representation

    if (!this.reflect)
        return jobject;

    // get all properties using reflection
    if (this.reflectfields) {
        try {
            for (Field field : cls.getDeclaredFields()) {
                Boolean access = field.isAccessible();
                field.setAccessible(true);

                int mod = field.getModifiers();
                String key = getKey(mod, field.getName());
                Object value;
                try {
                    value = field.get(object);
                } catch (Exception e) {
                    value = e.toString();
                }

                field.setAccessible(access);

                if (!this.reflectprivate && (Modifier.isPrivate(mod) || Modifier.isProtected(mod)))
                    continue;
                if (!this.reflectstatic && Modifier.isStatic(mod))
                    continue;

                addValue(jobject, key, value, depth);
            }
        } catch (SecurityException e) {
        }
    }

    // get all methods using reflection
    if (this.reflectmethods) {
        try {
            JSONObject methods = new JSONObject();
            for (Method method : cls.getDeclaredMethods()) {
                Boolean access = method.isAccessible();
                method.setAccessible(true);

                Class<?>[] params = method.getParameterTypes();
                StringBuilder parameters = new StringBuilder("");
                for (int i = 0, j = params.length; i < j; i++) {
                    parameters.append(params[i].getName());
                    if (i + 1 < j)
                        parameters.append(", ");
                }
                int mod = method.getModifiers();
                String key = getKey(mod, method.getName() + "(" + parameters.toString() + ")");
                String value = method.getReturnType().getName();

                method.setAccessible(access);

                if (!this.reflectprivate && (Modifier.isPrivate(mod) || Modifier.isProtected(mod)))
                    continue;
                if (!this.reflectstatic && Modifier.isStatic(mod))
                    continue;

                methods.put(key, value);
            }
            jobject.put("___methods", methods);
        } catch (SecurityException e) {
        }
    }

    return jobject;
}

From source file:edu.cmu.tetrad.util.TetradSerializableUtils.java

/**
 * Serializes the given class to the getCurrentDirectory() directory. The
 * static serializedInstance() method of clazz will be called to get an
 * examplar of clazz. This examplar will then be serialized out to a file
 * stored in getCurrentDirectory().//from   w  ww  .  j a  v a  2  s  .  c  o  m
 *
 * @param clazz the class to serialize.
 * @throws RuntimeException if clazz cannot be serialized. This exception
 *                          has an informative message and wraps the
 *                          originally thrown exception as root cause.
 * @see #getCurrentDirectory()
 */
private void serializeClass(Class clazz, Map<String, List<String>> classFields) throws RuntimeException {
    File current = new File(getCurrentDirectory());

    if (!current.exists() || !current.isDirectory()) {
        throw new IllegalStateException("There is no " + current.getAbsolutePath() + " directory. "
                + "\nThis is where the serialized classes should be. "
                + "Please run serializeCurrentDirectory() first.");
    }

    try {
        Field field = clazz.getDeclaredField("serialVersionUID");

        int modifiers = field.getModifiers();
        boolean _static = Modifier.isStatic(modifiers);
        boolean _final = Modifier.isFinal(modifiers);
        field.setAccessible(true);

        if (!_static || !_final || !(23L == field.getLong(null))) {
            throw new RuntimeException(
                    "Class " + clazz + " does not define static final " + "long serialVersionUID = 23L");
        }

        int numFields = getNumNonSerialVersionUIDFields(clazz);

        if (numFields > 0) {
            Method method = clazz.getMethod("serializableInstance");
            Object object = method.invoke(null);

            File file = new File(current, clazz.getName() + ".ser");
            boolean created = file.createNewFile();

            FileOutputStream out = new FileOutputStream(file);
            ObjectOutputStream objOut = new ObjectOutputStream(out);
            objOut.writeObject(object);
            out.close();
        }

        // Make entry in list of class fields.
        ObjectStreamClass objectStreamClass = ObjectStreamClass.lookup(clazz);
        String className = objectStreamClass.getName();
        ObjectStreamField[] fields = objectStreamClass.getFields();
        @SuppressWarnings("Convert2Diamond")
        List<String> fieldList = new ArrayList<>();

        for (ObjectStreamField objectStreamField : fields) {
            String fieldName = objectStreamField.getName();
            fieldList.add(fieldName);
        }

        classFields.put(className, fieldList);
    } catch (NoSuchFieldException e) {
        throw new RuntimeException(("There is no static final long field " + "'serialVersionUID' in " + clazz
                + ". Please make one and set it " + "to 23L."));
    } catch (NoSuchMethodException e) {
        throw new RuntimeException(
                "Class " + clazz + "does not " + "have a public static serializableInstance constructor.", e);
    } catch (IllegalAccessException e) {
        throw new RuntimeException(
                "The method serializableInstance() of " + "class " + clazz + " is not public.", e);
    } catch (InvocationTargetException e) {
        throw new RuntimeException(
                "Unable to statically call the " + "serializableInstance() method of class " + clazz + ".", e);
    } catch (IOException e) {
        throw new RuntimeException("Could not create a new, writeable file " + "in " + getCurrentDirectory()
                + " when trying to serialize " + clazz + ".", e);
    }
}

From source file:edu.cmu.tetradapp.util.TetradSerializableUtils.java

/**
 * Serializes the given class to the getCurrentDirectory() directory. The
 * static serializedInstance() method of clazz will be called to get an
 * examplar of clazz. This examplar will then be serialized out to a file
 * stored in getCurrentDirectory().// w w  w  . j a v a2s .  co  m
 *
 * @param clazz the class to serialize.
 * @throws RuntimeException if clazz cannot be serialized. This exception
 *                          has an informative message and wraps the
 *                          originally thrown exception as root cause.
 * @see #getCurrentDirectory()
 */
private void serializeClass(Class clazz, Map<String, List<String>> classFields) throws RuntimeException {
    File current = new File(getCurrentDirectory());

    if (!current.exists() || !current.isDirectory()) {
        throw new IllegalStateException("There is no " + current.getAbsolutePath() + " directory. "
                + "\nThis is where the serialized classes should be. "
                + "Please run serializeCurrentDirectory() first.");
    }

    try {
        Field field = clazz.getDeclaredField("serialVersionUID");

        int modifiers = field.getModifiers();
        boolean _static = Modifier.isStatic(modifiers);
        boolean _final = Modifier.isFinal(modifiers);
        field.setAccessible(true);

        if (!_static || !_final || !(23L == field.getLong(null))) {
            throw new RuntimeException(
                    "Class " + clazz + " does not define static final " + "long serialVersionUID = 23L");
        }

        int numFields = getNumNonSerialVersionUIDFields(clazz);

        if (numFields > 0) {
            Method method = clazz.getMethod("serializableInstance", new Class[0]);
            Object object = method.invoke(null, new Object[0]);

            File file = new File(current, clazz.getName() + ".ser");
            file.createNewFile();

            FileOutputStream out = new FileOutputStream(file);
            ObjectOutputStream objOut = new ObjectOutputStream(out);
            objOut.writeObject(object);
            out.close();
        }

        // Make entry in list of class fields.
        ObjectStreamClass objectStreamClass = ObjectStreamClass.lookup(clazz);
        String className = objectStreamClass.getName();
        ObjectStreamField[] fields = objectStreamClass.getFields();
        List<String> fieldList = new ArrayList<String>();

        for (ObjectStreamField objectStreamField : fields) {
            String fieldName = objectStreamField.getName();
            fieldList.add(fieldName);
        }

        classFields.put(className, fieldList);
    } catch (NoSuchFieldException e) {
        throw new RuntimeException(("There is no static final long field " + "'serialVersionUID' in " + clazz
                + ". Please make one and set it " + "to 23L."));
    } catch (NoSuchMethodException e) {
        throw new RuntimeException(
                "Class " + clazz + "does not " + "have a public static serializableInstance constructor.", e);
    } catch (IllegalAccessException e) {
        throw new RuntimeException(
                "The method serializableInstance() of " + "class " + clazz + " is not public.", e);
    } catch (InvocationTargetException e) {
        throw new RuntimeException(
                "Unable to statically call the " + "serializableInstance() method of class " + clazz + ".", e);
    } catch (IOException e) {
        throw new RuntimeException("Could not create a new, writeable file " + "in " + getCurrentDirectory()
                + " when trying to serialize " + clazz + ".", e);
    }
}