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.sm.query.utils.QueryUtils.java

/**
 * @param field//  www .jav  a2s  .co  m
 * @return true - for write able field
 */
public static boolean isSkipField(Field field) {
    int modifier = field.getModifiers();
    if (Modifier.isFinal(modifier) || Modifier.isStatic(modifier) || Modifier.isNative(modifier)
            || Modifier.isTransient(modifier))
        return true;
    else
        return false;
}

From source file:jp.co.ctc_g.jfw.core.util.Beans.java

private static Object readPseudoPropertyValueNamed0(String propertyName, Object bean) {
    Object value = null;/*w  ww . j  a va 2s  .c  o  m*/
    try {
        PropertyDescriptor pd = findPropertyDescriptorFor(bean.getClass(), propertyName);
        // ???????
        if (pd != null) {
            Method reader = pd.getReadMethod();
            if (reader != null) {
                reader.setAccessible(true);
                value = reader.invoke(bean);
            } else {
                if (L.isDebugEnabled()) {
                    Map<String, Object> replace = new HashMap<String, Object>(1);
                    replace.put("property", propertyName);
                    L.debug(Strings.substitute(R.getString("E-UTIL#0012"), replace));
                }
            }
            // ???????
        } else {
            Field f = bean.getClass().getField(propertyName);
            if (f != null && !Modifier.isStatic(f.getModifiers())) {
                f.setAccessible(true);
                value = f.get(bean);
            } else {
                if (L.isDebugEnabled()) {
                    Map<String, Object> replace = new HashMap<String, Object>(1);
                    replace.put("property", propertyName);
                    L.debug(Strings.substitute(R.getString("D-UTIL#0019"), replace));
                }
            }
        }
    } catch (SecurityException e) {
        throw new InternalException(Beans.class, "E-UTIL#0010", e);
    } catch (NoSuchFieldException e) {
        Map<String, String> replace = new HashMap<String, String>(1);
        replace.put("property", propertyName);
        throw new InternalException(Beans.class, "E-UTIL#0011", replace, e);
    } catch (IllegalArgumentException e) {
        Map<String, String> replace = new HashMap<String, String>(1);
        replace.put("property", propertyName);
        throw new InternalException(Beans.class, "E-UTIL#0012", replace, e);
    } catch (IllegalAccessException e) {
        throw new InternalException(Beans.class, "E-UTIL#0013", e);
    } catch (InvocationTargetException e) {
        Map<String, String> replace = new HashMap<String, String>(2);
        replace.put("class", bean.getClass().getName());
        replace.put("property", propertyName);
        throw new InternalException(Beans.class, "E-UTIL#0014", replace, e);
    }
    return value;
}

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

@SuppressWarnings("unchecked")
public static CaptureRequest.Builder deserialize(CaptureRequest.Builder mdDefault, JSONObject jsonReq)
        throws ItsException {
    try {/*from ww  w  . j  a v  a  2 s.co m*/
        Logt.i(TAG, "Parsing JSON capture request ...");

        // Iterate over the CaptureRequest reflected fields.
        CaptureRequest.Builder md = mdDefault;
        Field[] allFields = CaptureRequest.class.getDeclaredFields();
        for (Field field : allFields) {
            if (Modifier.isPublic(field.getModifiers()) && Modifier.isStatic(field.getModifiers())
                    && field.getType() == CaptureRequest.Key.class
                    && field.getGenericType() instanceof ParameterizedType) {
                ParameterizedType paramType = (ParameterizedType) field.getGenericType();
                Type[] argTypes = paramType.getActualTypeArguments();
                if (argTypes.length > 0) {
                    CaptureRequest.Key key = (CaptureRequest.Key) field.get(md);
                    String keyName = key.getName();
                    Type keyType = argTypes[0];

                    // For each reflected CaptureRequest entry, look inside the JSON object
                    // to see if it is being set. If it is found, remove the key from the
                    // JSON object. After this process, there should be no keys left in the
                    // JSON (otherwise an invalid key was specified).

                    if (jsonReq.has(keyName) && !jsonReq.isNull(keyName)) {
                        if (keyType instanceof GenericArrayType) {
                            Type elmtType = ((GenericArrayType) keyType).getGenericComponentType();
                            JSONArray ja = jsonReq.getJSONArray(keyName);
                            Object val[] = new Object[ja.length()];
                            for (int i = 0; i < ja.length(); i++) {
                                if (elmtType == int.class) {
                                    Array.set(val, i, ja.getInt(i));
                                } else if (elmtType == byte.class) {
                                    Array.set(val, i, (byte) ja.getInt(i));
                                } else if (elmtType == float.class) {
                                    Array.set(val, i, (float) ja.getDouble(i));
                                } else if (elmtType == long.class) {
                                    Array.set(val, i, ja.getLong(i));
                                } else if (elmtType == double.class) {
                                    Array.set(val, i, ja.getDouble(i));
                                } else if (elmtType == boolean.class) {
                                    Array.set(val, i, ja.getBoolean(i));
                                } else if (elmtType == String.class) {
                                    Array.set(val, i, ja.getString(i));
                                } else if (elmtType == Size.class) {
                                    JSONObject obj = ja.getJSONObject(i);
                                    Array.set(val, i, new Size(obj.getInt("width"), obj.getInt("height")));
                                } else if (elmtType == Rect.class) {
                                    JSONObject obj = ja.getJSONObject(i);
                                    Array.set(val, i, new Rect(obj.getInt("left"), obj.getInt("top"),
                                            obj.getInt("bottom"), obj.getInt("right")));
                                } else if (elmtType == Rational.class) {
                                    JSONObject obj = ja.getJSONObject(i);
                                    Array.set(val, i,
                                            new Rational(obj.getInt("numerator"), obj.getInt("denominator")));
                                } else if (elmtType == RggbChannelVector.class) {
                                    JSONArray arr = ja.getJSONArray(i);
                                    Array.set(val, i,
                                            new RggbChannelVector((float) arr.getDouble(0),
                                                    (float) arr.getDouble(1), (float) arr.getDouble(2),
                                                    (float) arr.getDouble(3)));
                                } else if (elmtType == ColorSpaceTransform.class) {
                                    JSONArray arr = ja.getJSONArray(i);
                                    Rational xform[] = new Rational[9];
                                    for (int j = 0; j < 9; j++) {
                                        xform[j] = new Rational(arr.getJSONObject(j).getInt("numerator"),
                                                arr.getJSONObject(j).getInt("denominator"));
                                    }
                                    Array.set(val, i, new ColorSpaceTransform(xform));
                                } else if (elmtType == MeteringRectangle.class) {
                                    JSONObject obj = ja.getJSONObject(i);
                                    Array.set(val, i, new MeteringRectangle(obj.getInt("x"), obj.getInt("y"),
                                            obj.getInt("width"), obj.getInt("height"), obj.getInt("weight")));
                                } else {
                                    throw new ItsException("Failed to parse key from JSON: " + keyName);
                                }
                            }
                            if (val != null) {
                                Logt.i(TAG, "Set: " + keyName + " -> " + Arrays.toString(val));
                                md.set(key, val);
                                jsonReq.remove(keyName);
                            }
                        } else {
                            Object val = null;
                            if (keyType == Integer.class) {
                                val = jsonReq.getInt(keyName);
                            } else if (keyType == Byte.class) {
                                val = (byte) jsonReq.getInt(keyName);
                            } else if (keyType == Double.class) {
                                val = jsonReq.getDouble(keyName);
                            } else if (keyType == Long.class) {
                                val = jsonReq.getLong(keyName);
                            } else if (keyType == Float.class) {
                                val = (float) jsonReq.getDouble(keyName);
                            } else if (keyType == Boolean.class) {
                                val = jsonReq.getBoolean(keyName);
                            } else if (keyType == String.class) {
                                val = jsonReq.getString(keyName);
                            } else if (keyType == Size.class) {
                                JSONObject obj = jsonReq.getJSONObject(keyName);
                                val = new Size(obj.getInt("width"), obj.getInt("height"));
                            } else if (keyType == Rect.class) {
                                JSONObject obj = jsonReq.getJSONObject(keyName);
                                val = new Rect(obj.getInt("left"), obj.getInt("top"), obj.getInt("right"),
                                        obj.getInt("bottom"));
                            } else if (keyType == Rational.class) {
                                JSONObject obj = jsonReq.getJSONObject(keyName);
                                val = new Rational(obj.getInt("numerator"), obj.getInt("denominator"));
                            } else if (keyType == RggbChannelVector.class) {
                                JSONObject obj = jsonReq.optJSONObject(keyName);
                                JSONArray arr = jsonReq.optJSONArray(keyName);
                                if (arr != null) {
                                    val = new RggbChannelVector((float) arr.getDouble(0),
                                            (float) arr.getDouble(1), (float) arr.getDouble(2),
                                            (float) arr.getDouble(3));
                                } else if (obj != null) {
                                    val = new RggbChannelVector((float) obj.getDouble("red"),
                                            (float) obj.getDouble("greenEven"),
                                            (float) obj.getDouble("greenOdd"), (float) obj.getDouble("blue"));
                                } else {
                                    throw new ItsException("Invalid RggbChannelVector object");
                                }
                            } else if (keyType == ColorSpaceTransform.class) {
                                JSONArray arr = jsonReq.getJSONArray(keyName);
                                Rational a[] = new Rational[9];
                                for (int i = 0; i < 9; i++) {
                                    a[i] = new Rational(arr.getJSONObject(i).getInt("numerator"),
                                            arr.getJSONObject(i).getInt("denominator"));
                                }
                                val = new ColorSpaceTransform(a);
                            } else if (keyType instanceof ParameterizedType
                                    && ((ParameterizedType) keyType).getRawType() == Range.class
                                    && ((ParameterizedType) keyType).getActualTypeArguments().length == 1
                                    && ((ParameterizedType) keyType)
                                            .getActualTypeArguments()[0] == Integer.class) {
                                JSONArray arr = jsonReq.getJSONArray(keyName);
                                val = new Range<Integer>(arr.getInt(0), arr.getInt(1));
                            } else {
                                throw new ItsException(
                                        "Failed to parse key from JSON: " + keyName + ", " + keyType);
                            }
                            if (val != null) {
                                Logt.i(TAG, "Set: " + keyName + " -> " + val);
                                md.set(key, val);
                                jsonReq.remove(keyName);
                            }
                        }
                    }
                }
            }
        }

        // Ensure that there were no invalid keys in the JSON request object.
        if (jsonReq.length() != 0) {
            throw new ItsException("Invalid JSON key(s): " + jsonReq.toString());
        }

        Logt.i(TAG, "Parsing JSON capture request completed");
        return md;
    } catch (java.lang.IllegalAccessException e) {
        throw new ItsException("Access error: ", e);
    } catch (org.json.JSONException e) {
        throw new ItsException("JSON error: ", e);
    }
}

From source file:org.apache.axis.utils.BeanUtils.java

public static BeanPropertyDescriptor[] processPropertyDescriptors(PropertyDescriptor[] rawPd, Class cls,
        TypeDesc typeDesc) {// w  ww.  j a v a2 s .  c  o  m

    // Create a copy of the rawPd called myPd
    BeanPropertyDescriptor[] myPd = new BeanPropertyDescriptor[rawPd.length];

    ArrayList pd = new ArrayList();

    try {
        for (int i = 0; i < rawPd.length; i++) {
            // Skip the special "any" field
            if (rawPd[i].getName().equals(Constants.ANYCONTENT))
                continue;
            pd.add(new BeanPropertyDescriptor(rawPd[i]));
        }

        // Now look for public fields
        Field fields[] = cls.getFields();
        if (fields != null && fields.length > 0) {
            // See if the field is in the list of properties
            // add it if not.
            for (int i = 0; i < fields.length; i++) {
                Field f = fields[i];
                // skip if field come from a java.* or javax.* package
                // WARNING: Is this going to make bad things happen for
                // users JavaBeans?  Do they WANT these fields serialzed?
                String clsName = f.getDeclaringClass().getName();
                if (clsName.startsWith("java.") || clsName.startsWith("javax.")) {
                    continue;
                }
                // skip field if it is final, transient, or static
                if (!(Modifier.isStatic(f.getModifiers()) || Modifier.isFinal(f.getModifiers())
                        || Modifier.isTransient(f.getModifiers()))) {
                    String fName = f.getName();
                    boolean found = false;
                    for (int j = 0; j < rawPd.length && !found; j++) {
                        String pName = ((BeanPropertyDescriptor) pd.get(j)).getName();
                        if (pName.length() == fName.length()
                                && pName.substring(0, 1).equalsIgnoreCase(fName.substring(0, 1))) {

                            found = pName.length() == 1 || pName.substring(1).equals(fName.substring(1));
                        }
                    }

                    if (!found) {
                        pd.add(new FieldPropertyDescriptor(f.getName(), f));
                    }
                }
            }
        }

        // If typeDesc meta data exists, re-order according to the fields
        if (typeDesc != null && typeDesc.getFields(true) != null) {
            ArrayList ordered = new ArrayList();
            // Add the TypeDesc elements first
            FieldDesc[] fds = typeDesc.getFields(true);
            for (int i = 0; i < fds.length; i++) {
                FieldDesc field = fds[i];
                if (field.isElement()) {
                    boolean found = false;
                    for (int j = 0; j < pd.size() && !found; j++) {
                        if (field.getFieldName().equals(((BeanPropertyDescriptor) pd.get(j)).getName())) {
                            ordered.add(pd.remove(j));
                            found = true;
                        }
                    }
                }
            }
            // Add the remaining elements
            while (pd.size() > 0) {
                ordered.add(pd.remove(0));
            }
            // Use the ordered list
            pd = ordered;
        }

        myPd = new BeanPropertyDescriptor[pd.size()];
        for (int i = 0; i < pd.size(); i++) {
            myPd[i] = (BeanPropertyDescriptor) pd.get(i);
        }
    } catch (Exception e) {
        log.error(Messages.getMessage("badPropertyDesc00", cls.getName()), e);
        throw new InternalException(e);
    }

    return myPd;
}

From source file:io.github.wysohn.triggerreactor.tools.ReflectionUtil.java

/**
 * https://stackoverflow.com/questions/3301635/change-private-static-final-field-using-java-reflection
 * @param field//  w w w . j av a2  s  .  c o m
 * @param newValue
 * @throws SecurityException
 * @throws NoSuchFieldException
 * @throws Exception
 */
private static void setFinalField(Object target, Field field, Object newValue) throws NoSuchFieldException {
    field.setAccessible(true);

    Field modifiersField = null;
    try {
        modifiersField = Field.class.getDeclaredField("modifiers");
    } catch (SecurityException e1) {
        e1.printStackTrace();
    }

    modifiersField.setAccessible(true);
    try {
        modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
    } catch (IllegalArgumentException | IllegalAccessException e) {
        e.printStackTrace();
    }

    try {
        field.set(target, newValue);
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }
}

From source file:utils.ReflectionService.java

public static JsonNode createJsonNode(Class clazz, int maxDeep) {

    if (maxDeep <= 0 || JsonNode.class.isAssignableFrom(clazz)) {
        return null;
    }//from  www .j a  v  a 2 s . c  o  m

    ObjectMapper objectMapper = new ObjectMapper();
    ObjectNode objectNode = objectMapper.createObjectNode();

    for (Field field : clazz.getDeclaredFields()) {
        field.setAccessible(true);
        String key = field.getName();
        try {
            // is array or collection
            if (field.getType().isArray() || Collection.class.isAssignableFrom(field.getType())) {
                ParameterizedType collectionType = (ParameterizedType) field.getGenericType();
                Class<?> type = (Class<?>) collectionType.getActualTypeArguments()[0];
                ArrayNode arrayNode = objectMapper.createArrayNode();
                arrayNode.add(createJsonNode(type, maxDeep - 1));
                objectNode.put(key, arrayNode);
            } else {
                Class<?> type = field.getType();
                if (Modifier.isStatic(field.getModifiers())) {
                    continue;
                } else if (type.isEnum()) {
                    objectNode.put(key, Enum.class.getName());
                } else if (!type.getName().startsWith("java") && !key.startsWith("_")) {
                    objectNode.put(key, createJsonNode(type, maxDeep - 1));
                } else {
                    objectNode.put(key, type.getName());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return objectNode;
}

From source file:com.gatf.executor.core.AcceptanceTestContext.java

public static Map<String, String> getHttpHeadersMap() throws Exception {
    Map<String, String> headers = new HashMap<String, String>();
    Field[] declaredFields = HttpHeaders.class.getDeclaredFields();
    for (Field field : declaredFields) {
        if (java.lang.reflect.Modifier.isStatic(field.getModifiers()) && field.getType().equals(String.class)) {
            headers.put(field.get(null).toString().toLowerCase(), field.get(null).toString());
        }/*from   w w  w. j a  va2s . c  o m*/
    }
    return headers;
}

From source file:adalid.core.XS1.java

static Collection<Field> getFields(Class<?> clazz, Class<?> top) throws SecurityException {
    ArrayList<Field> fields = new ArrayList<>();
    if (clazz == null || top == null) {
        return fields;
    }/*from   www. j  av  a2 s .  c  o  m*/
    int modifiers;
    boolean restricted;
    Class<?> superClazz = clazz.getSuperclass();
    if (superClazz == null) {
        logger.trace(clazz.getName());
    } else {
        logger.trace(clazz.getName() + " extends " + superClazz.getName());
        if (top.isAssignableFrom(superClazz)) {
            //              fields.addAll(getFields(superClazz, top));
            Collection<Field> superFields = getFields(superClazz, top);
            for (Field field : superFields) {
                modifiers = field.getModifiers();
                restricted = Modifier.isStatic(modifiers) || Modifier.isFinal(modifiers);
                if (restricted) {
                    continue;
                }
                fields.add(field);
            }
        }
    }
    if (top.isAssignableFrom(clazz)) {
        logger.trace("adding fields declared at " + clazz.getName());
        //          fields.addAll(Arrays.asList(clazz.getDeclaredFields()));
        Field[] declaredFields = clazz.getDeclaredFields();
        for (Field field : declaredFields) {
            modifiers = field.getModifiers();
            restricted = Modifier.isStatic(modifiers) || Modifier.isFinal(modifiers);
            if (restricted) {
                continue;
            }
            fields.add(field);
        }
    }
    return getRidOfDupFields(fields);
}

From source file:org.codehaus.griffon.commons.GriffonClassUtils.java

/**
 * Determine whether the field is declared public static
 * @param f//  w  w  w. jav a  2  s . c om
 * @return True if the field is declared public static
 */
public static boolean isPublicStatic(Field f) {
    final int modifiers = f.getModifiers();
    return Modifier.isPublic(modifiers) && Modifier.isStatic(modifiers);
}

From source file:com.shenit.commons.utils.GsonUtils.java

/**
 * ???./*from w w  w  . ja  v a  2s  .c o m*/
 * @param clazz
 * @return
 */
public static Field<?>[] serializeFields(Class<?> clazz) {
    if (REGISTERED_FIELDS.containsKey(clazz))
        return REGISTERED_FIELDS.get(clazz);
    java.lang.reflect.Field[] fields = clazz.getDeclaredFields();
    List<Field<?>> fs = Lists.newArrayList();
    SerializedName serializedName;
    JsonProperty jsonProp;
    IgnoreField ignore;
    for (java.lang.reflect.Field field : fields) {
        if (field == null)
            continue;
        serializedName = field.getAnnotation(SerializedName.class);
        jsonProp = field.getAnnotation(JsonProperty.class);
        ignore = field.getAnnotation(IgnoreField.class);
        if (ignore != null)
            continue;
        String name = null;
        if (serializedName != null) {
            name = serializedName.value();
        } else if (jsonProp != null) {
            name = jsonProp.value();
        } else {
            name = Modifier.isStatic(field.getModifiers()) ? null : field.getName();
        }
        if (name == null)
            continue;

        Default defVal = field.getDeclaredAnnotation(Default.class);
        fs.add(new Field(name, field.getName(), field.getType(), defVal == null ? null : defVal.value()));
    }
    Field<?>[] fsArray = fs.toArray(new Field<?>[0]);
    REGISTERED_FIELDS.put(clazz, fsArray);
    return fsArray;
}