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.onehippo.forge.utilities.hst.simpleocm.load.BeanLoaderImpl.java

/**
 * @see FieldSetter/*ww  w . j a v a 2 s . c o m*/
 * @see javax.jcr.Node#getNodes(String) for collections with path pattern
 */
public void setFieldValue(final Object obj, final Field field, final Node node, final String relativePath)
        throws ContentNodeBindingException {
    final Class<?> fieldType = field.getType();
    try {
        if (!field.isAccessible()) {
            field.setAccessible(true);
        }
        if ("*".equals(relativePath)) {
            setAnyPathCompoundCollections(obj, field, node);
        } else if (List.class.equals(fieldType)
                && GenericsUtil.getGenericAnnotation(field, 0, JcrNodeType.class) != null) {
            setCompoundCollection(obj, field, node.getNodes(relativePath), ArrayList.class); // NOSONAR (prevent warning about loose coupling; we need the ArrayList.class here)
        } else if (Set.class.equals(fieldType)
                && GenericsUtil.getGenericAnnotation(field, 0, JcrNodeType.class) != null) {
            setCompoundCollection(obj, field, node.getNodes(relativePath), HashSet.class); // NOSONAR (prevent warning about loose coupling; we need the HashSet.class here)
        } else if (fieldType.getAnnotation(JcrNodeType.class) != null) {
            setCompound(obj, field, node, relativePath);
        } else {
            setPrimitive(obj, field, node, relativePath);
        }
    } catch (IllegalAccessException accessException) {
        throw new ContentNodeBindingException(
                "Error setting the field '" + field.getName() + "' of type " + fieldType, accessException);
    } catch (RepositoryException repositoryException) {
        throw new ContentNodeBindingException("Error setting the field '" + field.getName() + "' of type "
                + fieldType + ", relative jcr path '" + relativePath + "'", repositoryException);
    } catch (InstantiationException instantiationException) {
        throw new ContentNodeBindingException(
                "Error setting the field '" + field.getName() + "' of type " + fieldType,
                instantiationException);
    }
}

From source file:com.nabla.wapp.server.csv.CsvReader.java

private void buildColumnList(final Class recordClass) {
    if (recordClass != null) {
        for (Field field : recordClass.getDeclaredFields()) {
            final ICsvField definition = field.getAnnotation(ICsvField.class);
            if (definition != null) {
                final ICsvSetter writer = cache.get(field.getType());
                Assert.notNull(writer,// w w  w. j av  a 2 s .  c  om
                        "no CSV setter defined for type '" + field.getType().getSimpleName() + "'");
                if (!field.isAccessible())
                    field.setAccessible(true); // in order to lift restriction on 'private' fields
                final ICsvColumn column = new CsvColumn(field, writer);
                expectedColumns.put(column.getName().toLowerCase(), column);
                columns.add(column);
            }
        }
        buildColumnList(recordClass.getSuperclass());
    }
}

From source file:com.nonninz.robomodel.RoboModel.java

private void loadField(Field field, Cursor query) throws DatabaseNotUpToDateException {
    final Class<?> type = field.getType();
    final boolean wasAccessible = field.isAccessible();
    final int columnIndex = query.getColumnIndex(field.getName());
    field.setAccessible(true);/*from   w w  w.  j  av a  2  s.c  o  m*/

    /*
     * TODO: There is the potential of a problem here:
     * What happens if the developer changes the type of a field between releases?
     *
     * If he saves first, then the column type will be changed (In the future).
     * If he loads first, we don't know if an Exception will be thrown if the
     * types are incompatible, because it's undocumented in the Cursor documentation.
     */

    try {
        if (type == String.class) {
            field.set(this, query.getString(columnIndex));
        } else if (type == Boolean.TYPE) {
            final boolean value = query.getInt(columnIndex) == 1 ? true : false;
            field.setBoolean(this, value);
        } else if (type == Byte.TYPE) {
            field.setByte(this, (byte) query.getShort(columnIndex));
        } else if (type == Double.TYPE) {
            field.setDouble(this, query.getDouble(columnIndex));
        } else if (type == Float.TYPE) {
            field.setFloat(this, query.getFloat(columnIndex));
        } else if (type == Integer.TYPE) {
            field.setInt(this, query.getInt(columnIndex));
        } else if (type == Long.TYPE) {
            field.setLong(this, query.getLong(columnIndex));
        } else if (type == Short.TYPE) {
            field.setShort(this, query.getShort(columnIndex));
        } else if (type.isEnum()) {
            final String string = query.getString(columnIndex);
            if (string != null && string.length() > 0) {
                final Object[] constants = type.getEnumConstants();
                final Method method = type.getMethod("valueOf", Class.class, String.class);
                final Object value = method.invoke(constants[0], type, string);
                field.set(this, value);
            }
        } else {
            // Try to de-json it (db column must be of type text)
            try {
                final Object value = mMapper.readValue(query.getString(columnIndex), field.getType());
                field.set(this, value);
            } catch (final Exception e) {
                final String msg = String.format("Type %s is not supported for field %s", type,
                        field.getName());
                Ln.w(e, msg);
                throw new IllegalArgumentException(msg);
            }
        }
    } catch (final IllegalAccessException e) {
        final String msg = String.format("Field %s is not accessible", type, field.getName());
        throw new IllegalArgumentException(msg);
    } catch (final NoSuchMethodException e) {
        // Should not happen
        throw new RuntimeException(e);
    } catch (final InvocationTargetException e) {
        // Should not happen
        throw new RuntimeException(e);
    } catch (IllegalStateException e) {
        // This is when there is no column in db, but there is in the model
        throw new DatabaseNotUpToDateException(e);
    } finally {
        field.setAccessible(wasAccessible);
    }
}

From source file:org.apache.nifi.web.security.spring.LoginIdentityProviderFactoryBean.java

private void performFieldInjection(final LoginIdentityProvider instance, final Class loginIdentityProviderClass)
        throws IllegalArgumentException, IllegalAccessException {
    for (final Field field : loginIdentityProviderClass.getDeclaredFields()) {
        if (field.isAnnotationPresent(LoginIdentityProviderContext.class)) {
            // make the method accessible
            final boolean isAccessible = field.isAccessible();
            field.setAccessible(true);/*from   w w  w .  jav  a  2s .  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);
                    }
                }

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

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

From source file:com.dotweblabs.twirl.gae.GaeUnmarshaller.java

private void setFieldValue(Field field, Object instance, Object value) {
    boolean accessible = field.isAccessible();
    Class<?> clazz = field.getType();
    try {/*www .java 2  s.  c  om*/
        if ((field.getModifiers() & java.lang.reflect.Modifier.FINAL) == java.lang.reflect.Modifier.FINAL) {
            // do nothing for a final field
            // usually static UID fields
        } else {
            if (field.getType().isPrimitive() && value == null) {
                Object defaultValue = PrimitiveDefaults.getDefaultValue(clazz);
                field.setAccessible(true);
                field.set(instance, defaultValue);
                field.setAccessible(accessible);
            } else {
                field.setAccessible(true);
                field.set(instance, value);
                field.setAccessible(accessible);
            }
        }
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }
}

From source file:ru.savvy.springjsf.system.CustomJsfInjectionProvider.java

private void injectFields(Object bean, Class<? extends Annotation> annotation)
        throws InjectionProviderException {
    // get current WebApplicationContext
    FacesContext fc = FacesContext.getCurrentInstance();
    if (fc == null) {
        throw new InjectionProviderException("Unable to get current Faces context",
                new NullPointerException("Faces context is null"));
    }//from w  w w  .  j a v  a 2 s.c om
    WebApplicationContext wac = FacesContextUtils.getWebApplicationContext(fc);
    if (wac == null) {
        throw new InjectionProviderException("Unable to get Spring WebApplicationContext",
                new NullPointerException("WebApplicationContext is null"));
    }
    Field[] fields = bean.getClass().getDeclaredFields();
    for (Field f : fields) {
        if (f.getAnnotationsByType(annotation).length > 0) {
            Class<?> typeClazz = f.getType();
            Object injection;
            try {
                injection = wac.getBean(typeClazz);
            } catch (NoSuchBeanDefinitionException e) {
                e.printStackTrace();
                throw new InjectionProviderException("Unable to inject bean of type " + typeClazz.toString(),
                        e);
            }
            if (!f.isAccessible()) {
                f.setAccessible(true);
            }
            try {
                f.set(bean, injection);
                if (logger.isDebugEnabled()) {
                    logger.debug("Injected field of type " + f.getType().getCanonicalName() + " into "
                            + bean.getClass().getCanonicalName());
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
    }

}

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

private Object[] getDeclaredFieldValues(Object testInstance, Field field, boolean isArray) {
    try {//from w ww. j  ava  2 s. co m
        boolean isAccessible = field.isAccessible();
        if (!isAccessible) {
            field.setAccessible(true);
        }
        Object[] result;
        if (isArray) {
            result = (Object[]) field.get(testInstance);
        } else {
            result = new Object[] { field.get(testInstance) };
        }
        field.setAccessible(isAccessible);
        return result;
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }
}

From source file:com.evolveum.midpoint.prism.marshaller.BeanMarshaller.java

/**
 * For cases when XSD complex type has a simple content. In that case the resulting class has @XmlValue annotation.
 *//*from   w  w  w .j  av a2s.  c o m*/
private <T> PrimitiveXNode<T> marshallBeanToPrimitive(Object bean, SerializationContext ctx, Field valueField)
        throws SchemaException {
    if (!valueField.isAccessible()) {
        valueField.setAccessible(true);
    }
    T value;
    try {
        value = (T) valueField.get(bean);
    } catch (IllegalArgumentException | IllegalAccessException e) {
        throw new SchemaException("Cannot get primitive value from field " + valueField.getName() + " of bean "
                + bean + ": " + e.getMessage(), e);
    }
    PrimitiveXNode<T> xnode = new PrimitiveXNode<>(value);
    Class<?> fieldType = valueField.getType();
    QName xsdType = XsdTypeMapper.toXsdType(fieldType);
    xnode.setTypeQName(xsdType);
    return xnode;
}

From source file:com.haulmont.cuba.core.sys.MetadataLoader.java

/**
 * Guesses id for a datatype registered in legacy datatypes.xml file.
 * For backward compatibility only./*from   www  .  j av a  2 s.  com*/
 */
protected String guessDatatypeId(Datatype datatype) {
    if (datatype instanceof BigDecimalDatatype)
        return "decimal";
    if (datatype instanceof BooleanDatatype)
        return "boolean";
    if (datatype instanceof ByteArrayDatatype)
        return "byteArray";
    if (datatype instanceof DateDatatype)
        return "date";
    if (datatype instanceof DateTimeDatatype)
        return "dateTime";
    if (datatype instanceof DoubleDatatype)
        return "double";
    if (datatype instanceof IntegerDatatype)
        return "int";
    if (datatype instanceof LongDatatype)
        return "long";
    if (datatype instanceof StringDatatype)
        return "string";
    if (datatype instanceof TimeDatatype)
        return "time";
    if (datatype instanceof UUIDDatatype)
        return "uuid";
    try {
        Field nameField = datatype.getClass().getField("NAME");
        if (Modifier.isStatic(nameField.getModifiers()) && nameField.isAccessible()) {
            return (String) nameField.get(null);
        }
    } catch (Exception e) {
        log.trace("Cannot get NAME static field value: " + e);
    }
    throw new IllegalStateException("Cannot guess id for datatype " + datatype);
}