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:org.apache.nifi.authorization.AuthorityProviderFactoryBean.java

private void performFieldInjection(final AuthorityProvider instance, final Class authorityProviderClass)
        throws IllegalArgumentException, IllegalAccessException {
    for (final Field field : authorityProviderClass.getDeclaredFields()) {
        if (field.isAnnotationPresent(AuthorityProviderContext.class)) {
            // make the method accessible
            final boolean isAccessible = field.isAccessible();
            field.setAccessible(true);/*from w w  w. j  a v a2 s  . c  om*/

            try {
                // get the type
                final Class<?> fieldType = field.getType();

                // only consider this field if it isn't set yet
                if (field.get(instance) == null) {
                    // look for well known types
                    if (NiFiProperties.class.isAssignableFrom(fieldType)) {
                        // nifi properties injection
                        field.set(instance, properties);
                    } else if (ApplicationContext.class.isAssignableFrom(fieldType)) {
                        // spring application context injection
                        field.set(instance, applicationContext);
                    }
                }

            } finally {
                field.setAccessible(isAccessible);
            }
        }
    }

    final Class parentClass = authorityProviderClass.getSuperclass();
    if (parentClass != null && AuthorityProvider.class.isAssignableFrom(parentClass)) {
        performFieldInjection(instance, parentClass);
    }
}

From source file:name.yumaa.ChromeLogger4J.java

/**
 * Converts an object to a better format for logging
 * @param object    variable to conver/*from  w w  w .  ja  v  a2 s  .  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:net.dmulloy2.ultimatearena.types.ArenaZone.java

protected final void loadFromDisk() throws Throwable {
    checkFile();/* w  w  w  . ja va2s. co  m*/

    YamlConfiguration config = new YamlConfiguration();
    config.load(file);

    Map<String, Object> values = config.getValues(false);

    // Versioning
    int version = 0;
    if (values.containsKey("version"))
        version = (int) values.get("version");

    // Conversion
    if (checkConversion(version))
        return;

    // Load
    for (Entry<String, Object> entry : values.entrySet()) {
        try {
            for (java.lang.reflect.Field field : ArenaZone.class.getDeclaredFields()) {
                if (field.getName().equalsIgnoreCase(entry.getKey())) {
                    boolean accessible = field.isAccessible();
                    field.setAccessible(true);
                    field.set(this, entry.getValue());
                    field.setAccessible(accessible);
                }
            }
        } catch (Throwable ex) {
        }
    }

    loadCustomOptions(config);
}

From source file:org.kuali.coeus.common.budget.framework.query.QueryList.java

/** returns the field value in the base bean for the specified field.
 * @param fieldName fieldname whose value has to be got.
 * @param baseBean Bean containing the field.
 * @return value of the field./*ww  w . j a  va 2s . c o  m*/
 */
private Object getFieldValue(String fieldName, Object baseBean) {
    Field field = null;
    Method method = null;
    Class dataClass = baseBean.getClass();
    Object value = null;

    try {
        field = dataClass.getDeclaredField(fieldName);
        if (!field.isAccessible()) {
            throw new NoSuchFieldException();
        }
    } catch (NoSuchFieldException noSuchFieldException) {
        try {
            String methodName = "get" + (fieldName.charAt(0) + "").toUpperCase() + fieldName.substring(1);
            method = dataClass.getMethod(methodName, null);
        } catch (NoSuchMethodException noSuchMethodException) {
            LOG.error(noSuchMethodException.getMessage(), noSuchMethodException);
        }
    }

    try {
        if (field != null && field.isAccessible()) {
            value = field.get(baseBean);
        } else {
            value = method.invoke(baseBean, null);
        }
    } catch (IllegalAccessException illegalAccessException) {
        LOG.error(illegalAccessException.getMessage(), illegalAccessException);
    } catch (InvocationTargetException invocationTargetException) {
        LOG.error(invocationTargetException.getMessage(), invocationTargetException);
    }
    return value;
}

From source file:net.dmulloy2.ultimatearena.types.ArenaZone.java

/**
 * {@inheritDoc}/*ww w .j av a 2s .c om*/
 */
@Override
public Map<String, Object> serialize() {
    Map<String, Object> data = new LinkedHashMap<>();

    for (java.lang.reflect.Field field : ArenaZone.class.getDeclaredFields()) {
        if (Modifier.isTransient(field.getModifiers()))
            continue;

        try {
            boolean accessible = field.isAccessible();

            field.setAccessible(true);

            if (field.getType().equals(Integer.TYPE)) {
                if (field.getInt(this) != 0)
                    data.put(field.getName(), field.getInt(this));
            } else if (field.getType().equals(Long.TYPE)) {
                if (field.getLong(this) != 0)
                    data.put(field.getName(), field.getLong(this));
            } else if (field.getType().equals(Boolean.TYPE)) {
                if (field.getBoolean(this))
                    data.put(field.getName(), field.getBoolean(this));
            } else if (field.getType().isAssignableFrom(Collection.class)) {
                if (!((Collection<?>) field.get(this)).isEmpty())
                    data.put(field.getName(), field.get(this));
            } else if (field.getType().isAssignableFrom(String.class)) {
                if ((String) field.get(this) != null)
                    data.put(field.getName(), field.get(this));
            } else if (field.getType().isAssignableFrom(Map.class)) {
                if (!((Map<?, ?>) field.get(this)).isEmpty())
                    data.put(field.getName(), field.get(this));
            } else {
                if (field.get(this) != null)
                    data.put(field.getName(), field.get(this));
            }

            field.setAccessible(accessible);
        } catch (Throwable ex) {
        }
    }

    data.put("version", CURRENT_VERSION);
    return data;
}

From source file:jenkins.plugins.shiningpanda.ShiningPandaTestCase.java

/**
 * Same as assertEqualBeans, but works on protected and private fields.
 * /*from  w w  w. jav  a 2s .  c o  m*/
 * @param lhs
 *            The initial object.
 * @param rhs
 *            The final object.
 * @param properties
 *            The properties to check.
 * @throws Exception
 */
public void assertEqualBeans2(Object lhs, Object rhs, String properties) throws Exception {
    assertNotNull("lhs is null", lhs);
    assertNotNull("rhs is null", rhs);
    for (String p : properties.split(",")) {
        PropertyDescriptor pd = PropertyUtils.getPropertyDescriptor(lhs, p);
        Object lp, rp;
        if (pd == null) {
            Field f = getField(lhs.getClass(), p);
            assertNotNull("No such property " + p + " on " + lhs.getClass(), f);
            boolean accessible = f.isAccessible();
            if (!accessible)
                f.setAccessible(true);
            lp = f.get(lhs);
            rp = f.get(rhs);
            f.setAccessible(accessible);
        } else {
            lp = PropertyUtils.getProperty(lhs, p);
            rp = PropertyUtils.getProperty(rhs, p);
        }

        if (lp != null && rp != null && lp.getClass().isArray() && rp.getClass().isArray()) {
            // deep array equality comparison
            int m = Array.getLength(lp);
            int n = Array.getLength(rp);
            assertEquals("Array length is different for property " + p, m, n);
            for (int i = 0; i < m; i++)
                assertEquals(p + "[" + i + "] is different", Array.get(lp, i), Array.get(rp, i));
            return;
        }

        assertEquals("Property " + p + " is different", lp, rp);
    }
}

From source file:org.kuali.kra.budget.calculator.QueryList.java

/** returns the field value in the base bean for the specified field.
 * @param fieldName fieldname whose value has to be got.
 * @param baseBean Bean containing the field.
 * @return value of the field.// w  ww.j a v  a  2 s .c  om
 */
private Object getFieldValue(String fieldName, Object baseBean) {
    Field field = null;
    Method method = null;
    Class dataClass = baseBean.getClass();
    Object value = null;

    try {
        field = dataClass.getDeclaredField(fieldName);
        if (!field.isAccessible()) {
            throw new NoSuchFieldException();
        }
    } catch (NoSuchFieldException noSuchFieldException) {
        try {
            String methodName = "get" + (fieldName.charAt(0) + "").toUpperCase() + fieldName.substring(1);
            method = dataClass.getMethod(methodName, null);
        } catch (NoSuchMethodException noSuchMethodException) {
            noSuchMethodException.printStackTrace();
        }
    }

    try {
        if (field != null && field.isAccessible()) {
            value = field.get(baseBean);
        } else {
            value = method.invoke(baseBean, null);
        }
    } catch (IllegalAccessException illegalAccessException) {
        illegalAccessException.printStackTrace();
    } catch (InvocationTargetException invocationTargetException) {
        invocationTargetException.printStackTrace();
    }
    return value;
}

From source file:com.p5solutions.core.utils.ReflectionUtility.java

/**
 * Gets the value.// ww w .  j a  v  a2s  .  c  o m
 * 
 * @param field
 *          the field
 * @param target
 *          the target
 * @return the value
 */
public static Object getValue(Field field, Object target) {
    Object val = null;
    boolean access = field.isAccessible();
    try {
        field.setAccessible(true);
        val = field.get(target);
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        field.setAccessible(access);
    }
    return val;
}

From source file:com.p5solutions.core.utils.ReflectionUtility.java

/**
 * Sets the value.//from  w ww. ja v a  2  s . c o  m
 * 
 * @param field
 *          the field
 * @param target
 *          the target
 * @param value
 *          the value
 */
public static void setValue(Field field, Object target, Object value) {
    try {
        boolean access = field.isAccessible();
        field.setAccessible(true);
        field.set(target, value);
        field.setAccessible(access);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.josso.selfservices.password.PasswordManagementServiceImpl.java

public void register(String processId, String name, Object extension) {

    if (log.isDebugEnabled())
        log.debug("Registering " + name);

    PasswordManagementProcess p = this.runningProcesses.get(processId);

    Class clazz = p.getClass();//from  ww w. j ava2s  .  c o  m

    while (clazz != null) {
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {

            if (log.isDebugEnabled())
                log.debug("Checking field : " + field.getName());

            if (field.isAnnotationPresent(Extension.class)) {

                Extension ex = field.getAnnotation(Extension.class);

                if (ex.value().equals(name)) {
                    log.debug("Injecting extension : " + name);
                    try {

                        // Make field accessible ...
                        if (!field.isAccessible()) {
                            field.setAccessible(true);
                        }
                        field.set(p, extension);
                        return;
                    } catch (IllegalAccessException e) {
                        log.error(e.getMessage(), e);
                    }
                }
            }
        }
        clazz = clazz.getSuperclass();
    }

}