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:solidstack.reflect.Dumper.java

public void dumpTo(Object o, DumpWriter out) {
    try {//from ww w  .j  a va  2  s  . c o m
        if (o == null) {
            out.append("<null>");
            return;
        }
        Class<?> cls = o.getClass();
        if (cls == String.class) {
            out.append("\"").append(((String) o).replace("\\", "\\\\").replace("\n", "\\n").replace("\r", "\\r")
                    .replace("\t", "\\t").replace("\"", "\\\"")).append("\"");
            return;
        }
        if (o instanceof CharSequence) {
            out.append("(").append(o.getClass().getName()).append(")");
            dumpTo(o.toString(), out);
            return;
        }
        if (cls == char[].class) {
            out.append("(char[])");
            dumpTo(String.valueOf((char[]) o), out);
            return;
        }
        if (cls == byte[].class) {
            out.append("byte[").append(Integer.toString(((byte[]) o).length)).append("]");
            return;
        }
        if (cls == Class.class) {
            out.append(((Class<?>) o).getCanonicalName()).append(".class");
            return;
        }
        if (cls == File.class) {
            out.append("File( \"").append(((File) o).getPath()).append("\" )");
            return;
        }
        if (cls == AtomicInteger.class) {
            out.append("AtomicInteger( ").append(Integer.toString(((AtomicInteger) o).get())).append(" )");
            return;
        }
        if (cls == AtomicLong.class) {
            out.append("AtomicLong( ").append(Long.toString(((AtomicLong) o).get())).append(" )");
            return;
        }
        if (o instanceof ClassLoader) {
            out.append(o.getClass().getCanonicalName());
            return;
        }

        if (cls == java.lang.Short.class || cls == java.lang.Long.class || cls == java.lang.Integer.class
                || cls == java.lang.Float.class || cls == java.lang.Byte.class
                || cls == java.lang.Character.class || cls == java.lang.Double.class
                || cls == java.lang.Boolean.class || cls == BigInteger.class || cls == BigDecimal.class) {
            out.append("(").append(cls.getSimpleName()).append(")").append(o.toString());
            return;
        }

        String className = cls.getCanonicalName();
        if (className == null)
            className = cls.getName();
        out.append(className);

        if (this.skip.contains(className) || o instanceof java.lang.Thread) {
            out.append(" (skipped)");
            return;
        }

        Integer id = this.visited.get(o);
        if (id == null) {
            id = ++this.id;
            this.visited.put(o, id);
            if (!this.hideIds)
                out.append(" <id=" + id + ">");
        } else {
            out.append(" <refid=" + id + ">");
            return;
        }

        if (cls.isArray()) {
            if (Array.getLength(o) == 0)
                out.append(" []");
            else {
                out.newlineOrSpace().append("[").newlineOrSpace().indent().setFirst();
                int rowCount = Array.getLength(o);
                for (int i = 0; i < rowCount; i++) {
                    out.comma();
                    dumpTo(Array.get(o, i), out);
                }
                out.newlineOrSpace().unIndent().append("]");
            }
        } else if (o instanceof Collection && !this.overriddenCollection.contains(className)) {
            Collection<?> list = (Collection<?>) o;
            if (list.isEmpty())
                out.append(" []");
            else {
                out.newlineOrSpace().append("[").newlineOrSpace().indent().setFirst();
                for (Object value : list) {
                    out.comma();
                    dumpTo(value, out);
                }
                out.newlineOrSpace().unIndent().append("]");
            }
        } else if (o instanceof Properties && !this.overriddenCollection.contains(className)) // Properties is a Map, so it must come before the Map
        {
            Field def = cls.getDeclaredField("defaults");
            if (!def.isAccessible())
                def.setAccessible(true);
            Properties defaults = (Properties) def.get(o);
            Hashtable<?, ?> map = (Hashtable<?, ?>) o;
            out.newlineOrSpace().append("[").newlineOrSpace().indent().setFirst();
            for (Map.Entry<?, ?> entry : map.entrySet()) {
                out.comma();
                dumpTo(entry.getKey(), out);
                out.append(": ");
                dumpTo(entry.getValue(), out);
            }
            if (defaults != null && !defaults.isEmpty()) {
                out.comma().append("defaults: ");
                dumpTo(defaults, out);
            }
            out.newlineOrSpace().unIndent().append("]");
        } else if (o instanceof Map && !this.overriddenCollection.contains(className)) {
            Map<?, ?> map = (Map<?, ?>) o;
            if (map.isEmpty())
                out.append(" []");
            else {
                out.newlineOrSpace().append("[").newlineOrSpace().indent().setFirst();
                for (Map.Entry<?, ?> entry : map.entrySet()) {
                    out.comma();
                    dumpTo(entry.getKey(), out);
                    out.append(": ");
                    dumpTo(entry.getValue(), out);
                }
                out.newlineOrSpace().unIndent().append("]");
            }
        } else if (o instanceof Method) {
            out.newlineOrSpace().append("{").newlineOrSpace().indent().setFirst();

            Field field = cls.getDeclaredField("clazz");
            if (!field.isAccessible())
                field.setAccessible(true);
            out.comma().append("clazz").append(": ");
            dumpTo(field.get(o), out);

            field = cls.getDeclaredField("name");
            if (!field.isAccessible())
                field.setAccessible(true);
            out.comma().append("name").append(": ");
            dumpTo(field.get(o), out);

            field = cls.getDeclaredField("parameterTypes");
            if (!field.isAccessible())
                field.setAccessible(true);
            out.comma().append("parameterTypes").append(": ");
            dumpTo(field.get(o), out);

            field = cls.getDeclaredField("returnType");
            if (!field.isAccessible())
                field.setAccessible(true);
            out.comma().append("returnType").append(": ");
            dumpTo(field.get(o), out);

            out.newlineOrSpace().unIndent().append("}");
        } else {
            ArrayList<Field> fields = new ArrayList<Field>();
            while (cls != Object.class) {
                Field[] fs = cls.getDeclaredFields();
                for (Field field : fs)
                    fields.add(field);
                cls = cls.getSuperclass();
            }

            Collections.sort(fields, new Comparator<Field>() {
                public int compare(Field left, Field right) {
                    return left.getName().compareTo(right.getName());
                }
            });

            if (fields.isEmpty())
                out.append(" {}");
            else {
                out.newlineOrSpace().append("{").newlineOrSpace().indent().setFirst();
                for (Field field : fields)
                    if ((field.getModifiers() & Modifier.STATIC) == 0)
                        if (!this.hideTransients || (field.getModifiers() & Modifier.TRANSIENT) == 0) {
                            out.comma().append(field.getName()).append(": ");

                            if (!field.isAccessible())
                                field.setAccessible(true);

                            if (field.getType().isPrimitive())
                                if (field.getType() == boolean.class) // TODO More?
                                    out.append(field.get(o).toString());
                                else
                                    out.append("(").append(field.getType().getName()).append(")")
                                            .append(field.get(o).toString());
                            else
                                dumpTo(field.get(o), out);
                        }
                out.newlineOrSpace().unIndent().append("}");
            }
        }
    } catch (IOException e) {
        throw new FatalIOException(e);
    } catch (Exception e) {
        dumpTo(e.toString(), out);
    }
}

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

@Override
public Map<String, Object> serialize() {
    Map<String, Object> data = new LinkedHashMap<>();

    for (Field field : ArenaConfig.class.getDeclaredFields()) {
        try {//from  w  ww  .j ava  2 s .  co  m
            if (Modifier.isTransient(field.getModifiers()))
                continue;

            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) {
        }
    }

    serializeCustomOptions(data);
    return data;
}

From source file:org.richfaces.tests.metamer.ftest.MatrixConfigurator.java

private void setDeclaredFieldValue(Object testInstance, Field field, Object assignment)
        throws IllegalArgumentException, IllegalAccessException {
    boolean isAccessible = field.isAccessible();
    if (!isAccessible) {
        field.setAccessible(true);/*from  www .  jav a2  s .  c  o m*/
    }
    field.set(testInstance, assignment);
    field.setAccessible(isAccessible);
}

From source file:org.ngrinder.model.BaseEntity.java

/**
 * Clone current entity./*from   w w w  .j a va2 s .c o  m*/
 *
 * Only not null value is merged.
 *
 * @param toInstance instance to which the value is copied.
 * @return cloned entity
 */
public M cloneTo(M toInstance) {
    Field forDisplay = null;
    try {
        Field[] fields = getClass().getDeclaredFields();
        // Iterate over all the attributes
        for (Field each : fields) {
            if (each.isSynthetic()) {
                continue;
            }
            final int modifiers = each.getModifiers();
            if (Modifier.isFinal(modifiers) || Modifier.isStatic(modifiers)) {
                continue;
            }
            forDisplay = each;
            final Cloneable annotation = each.getAnnotation(Cloneable.class);
            if (annotation == null) {
                continue;
            }
            if (!each.isAccessible()) {
                each.setAccessible(true);
            }
            each.set(toInstance, each.get(this));
        }
        return toInstance;
    } catch (Exception e) {
        String displayName = (forDisplay == null) ? "Empty" : forDisplay.getName();
        throw processException(displayName + " - Exception occurred while cloning an entity from " + this
                + " to " + toInstance, e);
    }
}

From source file:org.pentaho.hadoop.shim.HadoopConfigurationLocator.java

/**
 * Dynamically register a native library path. This relies on a specific implementation detail of ClassLoader: it's
 * usr_paths property./*from  w  ww .  ja  v a  2 s . c  o  m*/
 *
 * @param path Library path to add
 * @return {@code true} if the library path could be added successfully
 */
protected boolean registerNativeLibraryPath(String path) {
    if (path == null) {
        throw new NullPointerException();
    }
    path = path.trim();
    try {
        Field f = ClassLoader.class.getDeclaredField("usr_paths");
        boolean accessible = f.isAccessible();
        f.setAccessible(true);
        try {
            String[] paths = (String[]) f.get(null);

            // Make sure the path isn't already registered
            for (String p : paths) {
                if (p.equals(path)) {
                    return true; // Success, it's already there!
                }
            }

            String[] newPaths = new String[paths.length + 1];
            System.arraycopy(paths, 0, newPaths, 0, paths.length);
            newPaths[paths.length] = path;
            f.set(null, newPaths);
            // Success!
            return true;
        } finally {
            f.setAccessible(accessible);
        }
    } catch (Exception ex) {
        // Something went wrong, definitely not successful
        return false;
    }
}

From source file:com.flipkart.polyguice.dropwiz.DropConfigProvider.java

private Object getValueFromFields(String path, Class<?> type, Object inst) throws Exception {
    Field[] fields = type.getDeclaredFields();
    for (Field field : fields) {
        JsonProperty ann = field.getAnnotation(JsonProperty.class);
        if (ann != null) {
            String annName = ann.value();
            if (StringUtils.isBlank(annName)) {
                annName = ann.defaultValue();
            }/* w w  w  .j  ava  2 s  . c  om*/
            if (StringUtils.isBlank(annName)) {
                annName = field.getName();
            }
            if (StringUtils.equals(path, annName)) {
                boolean accessible = field.isAccessible();
                if (!accessible) {
                    field.setAccessible(true);
                }
                Object value = field.get(inst);
                if (!accessible) {
                    field.setAccessible(false);
                }
                return value;
            }
        }
    }
    return null;
}

From source file:de.codesourcery.eve.skills.util.XMLMapper.java

private BeanDescription createBeanDescription(Class<?> clasz) {

    BeanDescription result = new BeanDescription();
    for (java.lang.reflect.Field f : clasz.getDeclaredFields()) {
        final int modifiers = f.getModifiers();
        if (Modifier.isFinal(modifiers) || Modifier.isStatic(modifiers) || Modifier.isTransient(modifiers)) {
            continue;
        }//from   ww w. j  a  v a 2s  . c  o  m
        if (!f.isAccessible()) {
            f.setAccessible(true);
        }
        result.addField(f);
    }
    return result;
}

From source file:com.agimatec.validation.util.PropertyAccess.java

public Object get(Object bean) {
    try {/*ww  w.  ja va 2 s  .  c o m*/
        if (rememberField != null) { // cache field of previous access
            return rememberField.get(bean);
        }

        try { // try public method
            return getProperty(bean, propertyName);
        } catch (NoSuchMethodException ex) {
            Object value;
            try { // try public field
                Field aField = bean.getClass().getField(propertyName);
                value = aField.get(bean);
                rememberField = aField;
                return value;
            } catch (NoSuchFieldException ex2) {
                // search for private/protected field up the hierarchy
                Class theClass = bean.getClass();
                while (theClass != null) {
                    try {
                        Field aField = theClass.getDeclaredField(propertyName);
                        if (!aField.isAccessible()) {
                            aField.setAccessible(true);
                        }
                        value = aField.get(bean);
                        rememberField = aField;
                        return value;
                    } catch (NoSuchFieldException ex3) {
                        // do nothing
                    }
                    theClass = theClass.getSuperclass();
                }
                throw new IllegalArgumentException("cannot access field " + propertyName);
            }
        }
    } catch (IllegalArgumentException e) {
        throw e;
    } catch (Exception e) {
        throw new IllegalArgumentException("cannot access " + propertyName, e);
    }
}

From source file:org.apache.nifi.authorization.AuthorizerFactoryBean.java

private void performFieldInjection(final Authorizer instance, final Class authorizerClass)
        throws IllegalArgumentException, IllegalAccessException {
    for (final Field field : authorizerClass.getDeclaredFields()) {
        if (field.isAnnotationPresent(AuthorizerContext.class)) {
            // make the method accessible
            final boolean isAccessible = field.isAccessible();
            field.setAccessible(true);//from www. j  a v a 2 s.c  o  m

            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);
                    }
                }

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

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

From source file:com.meltmedia.jgroups.aws.AWS_PING.java

/**
 * Sets up the AmazonEC2Client to log soap faults from the AWS EC2 api server.
 *//* ww  w  .j a v a 2s.c  o m*/
private void setupAWSExceptionLogging() {
    boolean accessible = false;
    Field exceptionUnmarshallersField = null;
    try {
        exceptionUnmarshallersField = AmazonEC2Client.class.getDeclaredField("exceptionUnmarshallers");
        accessible = exceptionUnmarshallersField.isAccessible();
        exceptionUnmarshallersField.setAccessible(true);
        @SuppressWarnings("unchecked")
        List<Unmarshaller<AmazonServiceException, Node>> exceptionUnmarshallers = (List<Unmarshaller<AmazonServiceException, Node>>) exceptionUnmarshallersField
                .get(ec2);
        exceptionUnmarshallers.add(0, new AWSFaultLogger());
        ((AmazonEC2Client) ec2).addRequestHandler((RequestHandler) exceptionUnmarshallers.get(0));
    } catch (Throwable t) {
        //I don't care about this.
    } finally {
        if (exceptionUnmarshallersField != null) {
            try {
                exceptionUnmarshallersField.setAccessible(accessible);
            } catch (SecurityException se) {
                //I don't care about this.
            }
        }
    }
}