Example usage for java.lang.reflect Field isAccessible

List of usage examples for java.lang.reflect Field isAccessible

Introduction

In this page you can find the example usage for java.lang.reflect Field isAccessible.

Prototype

@Deprecated(since = "9")
public boolean isAccessible() 

Source Link

Document

Get the value of the accessible flag for this reflected object.

Usage

From source file:com.dubsar_dictionary.Dubsar.FAQActivity.java

/**
 * Set Proxy for Android 3.2 and below.//from  w  w  w .  j a  v a  2 s.com
 */
@SuppressWarnings("all")
private static boolean setProxyUpToHC(WebView webview, String host, int port) {
    Log.d(LOG_TAG, "Setting proxy with <= 3.2 API.");

    HttpHost proxyServer = new HttpHost(host, port);
    // Getting network
    Class networkClass = null;
    Object network = null;
    try {
        networkClass = Class.forName("android.webkit.Network");
        if (networkClass == null) {
            Log.e(LOG_TAG, "failed to get class for android.webkit.Network");
            return false;
        }
        Method getInstanceMethod = networkClass.getMethod("getInstance", Context.class);
        if (getInstanceMethod == null) {
            Log.e(LOG_TAG, "failed to get getInstance method");
        }
        network = getInstanceMethod.invoke(networkClass, new Object[] { webview.getContext() });
    } catch (Exception ex) {
        Log.e(LOG_TAG, "error getting network: " + ex);
        return false;
    }
    if (network == null) {
        Log.e(LOG_TAG, "error getting network: network is null");
        return false;
    }
    Object requestQueue = null;
    try {
        Field requestQueueField = networkClass.getDeclaredField("mRequestQueue");
        requestQueue = getFieldValueSafely(requestQueueField, network);
    } catch (Exception ex) {
        Log.e(LOG_TAG, "error getting field value");
        return false;
    }
    if (requestQueue == null) {
        Log.e(LOG_TAG, "Request queue is null");
        return false;
    }
    Field proxyHostField = null;
    try {
        Class requestQueueClass = Class.forName("android.net.http.RequestQueue");
        proxyHostField = requestQueueClass.getDeclaredField("mProxyHost");
    } catch (Exception ex) {
        Log.e(LOG_TAG, "error getting proxy host field");
        return false;
    }

    boolean temp = proxyHostField.isAccessible();
    try {
        proxyHostField.setAccessible(true);
        proxyHostField.set(requestQueue, proxyServer);
    } catch (Exception ex) {
        Log.e(LOG_TAG, "error setting proxy host");
    } finally {
        proxyHostField.setAccessible(temp);
    }

    Log.d(LOG_TAG, "Setting proxy with <= 3.2 API successful!");
    return true;
}

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

/**
 * Read a Field.//ww w .ja  v  a 2 s .  co  m
 * 
 * @param field the field to use
 * @param target the object to call on, may be null for static fields
 * @param forceAccess whether to break scope restrictions using the
 *            <code>setAccessible</code> method.
 * @return the field value
 * @throws IllegalArgumentException if the field is null
 * @throws IllegalAccessException if the field is not made accessible
 */
public static Object readField(Field field, Object target, boolean forceAccess) throws IllegalAccessException {
    if (field == null) {
        throw new IllegalArgumentException("The field must not be null");
    }
    if (forceAccess && !field.isAccessible()) {
        field.setAccessible(true);
    } else {
        MemberUtils.setAccessibleWorkaround(field);
    }
    return field.get(target);
}

From source file:com.unovo.frame.utils.SharedPreferencesHelper.java

@SuppressWarnings("TryWithIdenticalCatches")
private static <T> Object buildTargetFromSource(Class<T> clx, T target, String preFix, Set<String> existKeys,
        SharedPreferences sp) {/*from  w  w w.  j  a v a2 s . c  o m*/
    // Each to Object
    if (clx == null || clx.equals(Object.class)) {
        return target;
    }

    // Create instance
    if (target == null) {
        try {
            target = clx.newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
            return null;
        } catch (IllegalAccessException e) {
            e.printStackTrace();
            return null;
        }
    }

    // Get the class fields
    Field[] fields = clx.getDeclaredFields();
    if (fields == null || fields.length == 0)
        return target;

    // Foreach fields
    for (Field field : fields) {
        if (isContSupport(field))
            continue;

        final String fieldName = field.getName();
        Class<?> fieldType = field.getType();

        // Change the Field accessible status
        boolean isAccessible = field.isAccessible();
        if (!isAccessible)
            field.setAccessible(true);

        // Build the key
        String key = preFix + fieldName;
        // Get target value
        Object value = null;
        if (isBasicType(fieldType)) {
            if (existKeys.contains(key)) {
                // From the share map
                if (fieldType.equals(Byte.class) || fieldType.equals(byte.class)) {
                    value = (byte) sp.getInt(key, 0);
                } else if (fieldType.equals(Short.class) || fieldType.equals(short.class)) {
                    value = (short) sp.getInt(key, 0);
                } else if (fieldType.equals(Integer.class) || fieldType.equals(int.class)) {
                    value = sp.getInt(key, 0);
                } else if (fieldType.equals(Long.class) || fieldType.equals(long.class)) {
                    value = sp.getLong(key, 0);
                } else if (fieldType.equals(Float.class) || fieldType.equals(float.class)) {
                    value = sp.getFloat(key, 0);
                } else if (fieldType.equals(Double.class) || fieldType.equals(double.class)) {
                    value = Double.valueOf(sp.getString(key, "0.00"));
                } else if (fieldType.equals(Boolean.class) || fieldType.equals(boolean.class)) {
                    value = sp.getBoolean(key, false);
                } else if (fieldType.equals(Character.class) || fieldType.equals(char.class)) {
                    value = sp.getString(key, "").charAt(0);
                } else if (fieldType.equals(String.class)) {
                    value = sp.getString(key, "");
                }
            }
        } else {
            value = buildTargetFromSource(fieldType, null, preFix + fieldName + SEPARATOR, existKeys, sp);
        }

        // Set the field value
        if (value != null) {
            try {
                field.set(target, value);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
                Logger.e(TAG,
                        String.format("Set field error, Key:%s, type:%s, value:%s", key, fieldType, value));
            }
        } else {
            Logger.e(TAG, String.format("Get field value error, Key:%s, type:%s", key, fieldType));
        }
    }

    // Get super class fields
    return buildTargetFromSource(clx.getSuperclass(), target, preFix, existKeys, sp);
}

From source file:org.dcm4che3.conf.core.misc.DeepEquals.java

/**
 * Get all non static, non transient, fields of the passed in class.
 * The special this$ field is also not returned.  The result is cached
 * in a static ConcurrentHashMap to benefit execution performance.
 * @param c Class instance/*from www  . ja v a 2s.com*/
 * @return Collection of only the fields in the passed in class
 * that would need further processing (reference fields).  This
 * makes field traversal on a class faster as it does not need to
 * continually process known fields like primitives.
 */
public static Collection<Field> getDeepDeclaredFields(Class c) {
    if (_reflectedFields.containsKey(c)) {
        return _reflectedFields.get(c);
    }
    Collection<Field> fields = new ArrayList<Field>();
    Class curr = c;

    while (curr != null) {
        try {
            Field[] local = curr.getDeclaredFields();

            for (Field field : local) {
                if (!field.isAccessible()) {
                    try {
                        field.setAccessible(true);
                    } catch (Exception ignored) {
                    }
                }

                int modifiers = field.getModifiers();
                if (!Modifier.isStatic(modifiers) && !field.getName().startsWith("this$")
                        && !Modifier.isTransient(modifiers)) { // speed up: do not count static fields, not go back up to enclosing object in nested case    
                    fields.add(field);
                }
            }
        } catch (ThreadDeath t) {
            throw t;
        } catch (Throwable ignored) {
        }

        curr = curr.getSuperclass();
    }
    _reflectedFields.put(c, fields);
    return fields;
}

From source file:eu.vital.vitalcep.restApp.cepRESTApi.CEPICO.java

public static int getPid(Process process) {
    try {/*from w  ww.  ja  v a2  s .c  o m*/
        Class<?> cProcessImpl = process.getClass();
        java.lang.reflect.Field fPid = cProcessImpl.getDeclaredField("pid");
        if (!fPid.isAccessible()) {
            fPid.setAccessible(true);
        }
        return fPid.getInt(process);
    } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {
        return -1;
    }
}

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

/**
 * Write a field./*w w w . j a va 2 s  .  c o m*/
 * 
 * @param field to write
 * @param target the object to call on, may be null for static fields
 * @param value to set
 * @param forceAccess whether to break scope restrictions using the
 *            <code>setAccessible</code> method. <code>False</code> will
 *            only match public fields.
 * @throws IllegalArgumentException if the field is null
 * @throws IllegalAccessException if the field is not made accessible or is
 *             final
 */
public static void writeField(Field field, Object target, Object value, boolean forceAccess)
        throws IllegalAccessException {
    if (field == null) {
        throw new IllegalArgumentException("The field must not be null");
    }
    if (forceAccess && !field.isAccessible()) {
        field.setAccessible(true);
    } else {
        MemberUtils.setAccessibleWorkaround(field);
    }
    field.set(target, value);
}

From source file:eu.vital.vitalcep.restApp.alert.Alerts.java

public static int getPid(Process process) {
    try {/*  w  w w  . j  av a 2s .  c  om*/
        Class<?> cProcessImpl = process.getClass();
        java.lang.reflect.Field fPid = cProcessImpl.getDeclaredField("pid");
        if (!fPid.isAccessible()) {
            fPid.setAccessible(true);
        }
        return fPid.getInt(process);
    } catch (Exception e) {
        return -1;
    }
}

From source file:com.zlfun.framework.excel.ExcelUtils.java

private static String get(Object obj, Field field) {

    try {/*from   w  w w  .  j  a v  a2 s  . c  o m*/
        if (!field.isAccessible()) {
            field.setAccessible(true);
        }

        if (field.getType() == int.class) {
            return String.valueOf(field.getInt(obj));

        } else if (field.getType() == long.class) {
            return String.valueOf(field.getLong(obj));

        } else if (field.getType() == double.class) {
            return String.valueOf(field.getDouble(obj));
        } else if (field.getType() == byte.class) {
            return String.valueOf(field.getByte(obj));
        } else if (field.getType() == boolean.class) {
            return String.valueOf(field.getBoolean(obj));
        } else if (field.getType() == String.class) {
            if (field.get(obj) == null) {
                return "";
            }
            return String.valueOf(field.get(obj));
        } else if (field.getType() == Date.class) {
            if (field.get(obj) == null) {
                return "";
            }
            return MiscDateUtils.getDateTime((Date) field.get(obj));
        }

    } catch (Exception e) {

    }
    return "";
}

From source file:org.rhq.enterprise.server.safeinvoker.HibernateDetachUtility.java

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

    boolean accessModifierFlag = false;
    for (Field field : classFields) {
        accessModifierFlag = false;/*  w  w  w  .j  av a2s .  c om*/
        if (!field.isAccessible()) {
            field.setAccessible(true);
            accessModifierFlag = true;
        }

        Object fieldValue = field.get(object);

        if (fieldValue instanceof HibernateProxy) {

            Object replacement = null;
            String assistClassName = fieldValue.getClass().getName();
            if (assistClassName.contains("javassist") || assistClassName.contains("EnhancerByCGLIB")) {

                Class assistClass = fieldValue.getClass();
                try {
                    Method m = assistClass.getMethod("writeReplace");
                    replacement = m.invoke(fieldValue);

                    String assistNameDelimiter = assistClassName.contains("javassist") ? "_$$_" : "$$";

                    assistClassName = assistClassName.substring(0,
                            assistClassName.indexOf(assistNameDelimiter));
                    if (!replacement.getClass().getName().contains("hibernate")) {
                        nullOutUninitializedFields(replacement, checkedObjects, checkedObjectCollisionMap,
                                depth + 1, serializationType);

                        field.set(object, replacement);
                    } else {
                        replacement = null;
                    }
                } catch (Exception e) {
                    LOG.error("Unable to write replace object " + fieldValue.getClass(), e);
                }
            }

            if (replacement == null) {

                String className = ((HibernateProxy) fieldValue).getHibernateLazyInitializer().getEntityName();

                //see if there is a context classloader we should use instead of the current one.
                ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();

                Class clazz = contextClassLoader == null ? Class.forName(className)
                        : Class.forName(className, true, contextClassLoader);
                Class[] constArgs = { Integer.class };
                Constructor construct = null;

                try {
                    construct = clazz.getConstructor(constArgs);
                    replacement = construct.newInstance((Integer) ((HibernateProxy) fieldValue)
                            .getHibernateLazyInitializer().getIdentifier());
                    field.set(object, replacement);
                } catch (NoSuchMethodException nsme) {

                    try {
                        Field idField = clazz.getDeclaredField("id");
                        Constructor ct = clazz.getDeclaredConstructor();
                        ct.setAccessible(true);
                        replacement = ct.newInstance();
                        if (!idField.isAccessible()) {
                            idField.setAccessible(true);
                        }
                        idField.set(replacement, (Integer) ((HibernateProxy) fieldValue)
                                .getHibernateLazyInitializer().getIdentifier());
                    } catch (Exception e) {
                        e.printStackTrace();
                        LOG.error("No id constructor and unable to set field id for base bean " + className, e);
                    }

                    field.set(object, replacement);
                }
            }

        } else {
            if (fieldValue instanceof org.hibernate.collection.PersistentCollection) {
                // Replace hibernate specific collection types

                if (!((org.hibernate.collection.PersistentCollection) fieldValue).wasInitialized()) {
                    field.set(object, null);
                } else {

                    Object replacement = null;
                    boolean needToNullOutFields = true; // needed for BZ 688000
                    if (fieldValue instanceof Map) {
                        replacement = new HashMap((Map) fieldValue);
                    } else if (fieldValue instanceof List) {
                        replacement = new ArrayList((List) fieldValue);
                    } else if (fieldValue instanceof Set) {
                        ArrayList l = new ArrayList((Set) fieldValue); // cannot recurse Sets, see BZ 688000
                        nullOutUninitializedFields(l, checkedObjects, checkedObjectCollisionMap, depth + 1,
                                serializationType);
                        replacement = new HashSet(l); // convert it back to a Set since that's the type of the real collection, see BZ 688000
                        needToNullOutFields = false;
                    } else if (fieldValue instanceof Collection) {
                        replacement = new ArrayList((Collection) fieldValue);
                    }
                    setField(object, field.getName(), replacement);

                    if (needToNullOutFields) {
                        nullOutUninitializedFields(replacement, checkedObjects, checkedObjectCollisionMap,
                                depth + 1, serializationType);
                    }
                }

            } else {
                if (fieldValue != null && (fieldValue.getClass().getName().contains("org.rhq")
                        || fieldValue instanceof Collection || fieldValue instanceof Object[]
                        || fieldValue instanceof Map))
                    nullOutUninitializedFields((fieldValue), checkedObjects, checkedObjectCollisionMap,
                            depth + 1, serializationType);
            }
        }
        if (accessModifierFlag) {
            field.setAccessible(false);
        }
    }

}

From source file:com.ppp.prm.portal.server.service.gwt.HibernateDetachUtility.java

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

    boolean accessModifierFlag = false;
    for (Field field : classFields) {
        accessModifierFlag = false;/*from ww  w  . j  a  v a 2  s.  com*/
        if (!field.isAccessible()) {
            field.setAccessible(true);
            accessModifierFlag = true;
        }

        Object fieldValue = field.get(object);

        if (fieldValue instanceof HibernateProxy) {

            Object replacement = null;
            String assistClassName = fieldValue.getClass().getName();
            if (assistClassName.contains("javassist") || assistClassName.contains("EnhancerByCGLIB")) {

                Class assistClass = fieldValue.getClass();
                try {
                    Method m = assistClass.getMethod("writeReplace");
                    replacement = m.invoke(fieldValue);

                    String assistNameDelimiter = assistClassName.contains("javassist") ? "_$$_" : "$$";

                    assistClassName = assistClassName.substring(0,
                            assistClassName.indexOf(assistNameDelimiter));
                    if (!replacement.getClass().getName().contains("hibernate")) {
                        nullOutUninitializedFields(replacement, checkedObjects, checkedObjectCollisionMap,
                                depth + 1, serializationType);

                        field.set(object, replacement);
                    } else {
                        replacement = null;
                    }
                } catch (Exception e) {
                    LOG.error("Unable to write replace object " + fieldValue.getClass(), e);
                }
            }

            if (replacement == null) {

                String className = ((HibernateProxy) fieldValue).getHibernateLazyInitializer().getEntityName();

                //see if there is a context classloader we should use instead of the current one.
                ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();

                Class clazz = contextClassLoader == null ? Class.forName(className)
                        : Class.forName(className, true, contextClassLoader);
                Class[] constArgs = { Integer.class };
                Constructor construct = null;

                try {
                    construct = clazz.getConstructor(constArgs);
                    replacement = construct.newInstance((Integer) ((HibernateProxy) fieldValue)
                            .getHibernateLazyInitializer().getIdentifier());
                    field.set(object, replacement);
                } catch (NoSuchMethodException nsme) {

                    try {
                        Field idField = clazz.getDeclaredField("id");
                        Constructor ct = clazz.getDeclaredConstructor();
                        ct.setAccessible(true);
                        replacement = ct.newInstance();
                        if (!idField.isAccessible()) {
                            idField.setAccessible(true);
                        }
                        idField.set(replacement, (Integer) ((HibernateProxy) fieldValue)
                                .getHibernateLazyInitializer().getIdentifier());
                    } catch (Exception e) {
                        e.printStackTrace();
                        LOG.error("No id constructor and unable to set field id for base bean " + className, e);
                    }

                    field.set(object, replacement);
                }
            }

        } else {
            if (fieldValue instanceof org.hibernate.collection.PersistentCollection) {
                // Replace hibernate specific collection types

                if (!((org.hibernate.collection.PersistentCollection) fieldValue).wasInitialized()) {
                    field.set(object, null);
                } else {

                    Object replacement = null;
                    boolean needToNullOutFields = true; // needed for BZ 688000
                    if (fieldValue instanceof Map) {
                        replacement = new HashMap((Map) fieldValue);
                    } else if (fieldValue instanceof List) {
                        replacement = new ArrayList((List) fieldValue);
                    } else if (fieldValue instanceof Set) {
                        ArrayList l = new ArrayList((Set) fieldValue); // cannot recurse Sets, see BZ 688000
                        nullOutUninitializedFields(l, checkedObjects, checkedObjectCollisionMap, depth + 1,
                                serializationType);
                        replacement = new HashSet(l); // convert it back to a Set since that's the type of the real collection, see BZ 688000
                        needToNullOutFields = false;
                    } else if (fieldValue instanceof Collection) {
                        replacement = new ArrayList((Collection) fieldValue);
                    }
                    setField(object, field.getName(), replacement);

                    if (needToNullOutFields) {
                        nullOutUninitializedFields(replacement, checkedObjects, checkedObjectCollisionMap,
                                depth + 1, serializationType);
                    }
                }

            } else {
                if (fieldValue != null && (fieldValue.getClass().getName().contains("com.ppp")
                        || fieldValue instanceof Collection || fieldValue instanceof Object[]
                        || fieldValue instanceof Map))
                    nullOutUninitializedFields((fieldValue), checkedObjects, checkedObjectCollisionMap,
                            depth + 1, serializationType);
            }
        }
        if (accessModifierFlag) {
            field.setAccessible(false);
        }
    }

}