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.cloudbees.jenkins.plugins.enterpriseplugins.CloudBeesUpdateSite.java

/**
 * Sets the data timestamp (and tries to propagate the change to {@link UpdateSite#dataTimestamp}
 *
 * @param dataTimestamp the new data timestamp.
 */// w  w w.  j a  v  a2 s . co  m
private void setDataTimestamp(long dataTimestamp) {
    try {
        // try reflection to be safe for the parent class changing the location
        Field field = UpdateSite.class.getDeclaredField("dataTimestamp");
        boolean accessible = field.isAccessible();
        try {
            field.setLong(this, dataTimestamp);
        } finally {
            if (!accessible) {
                field.setAccessible(false);
            }
        }
    } catch (Throwable e) {
        // ignore
    }
    this.dataTimestamp = dataTimestamp;
}

From source file:com.brienwheeler.lib.svc.impl.StartableServiceBase.java

private void autoStartSubServices(Class<? extends IStartableService> clazz) throws InterruptedException {
    // do any superclass services first
    if (IStartableService.class.isAssignableFrom(clazz.getSuperclass()))
        autoStartSubServices(clazz.getSuperclass().asSubclass(IStartableService.class));

    for (Field field : clazz.getDeclaredFields()) {
        if (IStartableService.class.isAssignableFrom(field.getType())) {
            boolean setInaccessible = false;
            if (!field.isAccessible()) {
                field.setAccessible(true);
                setInaccessible = true;/*from  w  w w  .j a v a2s .  co  m*/
            }
            try {
                Object value = field.get(this);
                if (value != null)
                    startSubService((IStartableService) value);
            } catch (IllegalAccessException e) {
                throw new RuntimeException("error accessing IStartableService field " + field.getName(), e);
            } finally {
                if (setInaccessible)
                    field.setAccessible(false);
            }
        }
    }
}

From source file:org.apache.nifi.registry.security.authentication.IdentityProviderFactory.java

private void performFieldInjection(final IdentityProvider instance, final Class loginIdentityProviderClass)
        throws IllegalArgumentException, IllegalAccessException {
    for (final Field field : loginIdentityProviderClass.getDeclaredFields()) {
        if (field.isAnnotationPresent(IdentityProviderContext.class)) {
            // make the method accessible
            final boolean isAccessible = field.isAccessible();
            field.setAccessible(true);/*w w  w . j a  v  a 2  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 (NiFiRegistryProperties.class.isAssignableFrom(fieldType)) {
                        // nifi properties injection
                        field.set(instance, properties);
                    }
                }

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

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

From source file:de.digiway.rapidbreeze.server.infrastructure.objectstorage.ObjectStorage.java

private Map<String, String> getPersistedFields(Object obj) {
    Map<String, String> fields = new HashMap<>();
    for (Field field : obj.getClass().getDeclaredFields()) {
        if (isFieldPersistable(field)) {
            try {
                if (!field.isAccessible()) {
                    field.setAccessible(true);
                }/*w  w w.j a  v a  2  s  . c  o  m*/
                Object value = field.get(obj);
                fields.put(field.getName(), objectToString(value));
            } catch (IllegalArgumentException | IllegalAccessException ex) {
                throw new IllegalArgumentException("Cannot retrieve fields to persist.", ex);
            }
        }
    }
    return fields;
}

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

void saveField(Field field, TypedContentValues cv) {
    final Class<?> type = field.getType();
    final boolean wasAccessible = field.isAccessible();
    field.setAccessible(true);/*from w  ww . j  ava  2  s. co m*/

    try {
        if (type == String.class) {
            cv.put(field.getName(), (String) field.get(this));
        } else if (type == Boolean.TYPE) {
            cv.put(field.getName(), field.getBoolean(this));
        } else if (type == Byte.TYPE) {
            cv.put(field.getName(), field.getByte(this));
        } else if (type == Double.TYPE) {
            cv.put(field.getName(), field.getDouble(this));
        } else if (type == Float.TYPE) {
            cv.put(field.getName(), field.getFloat(this));
        } else if (type == Integer.TYPE) {
            cv.put(field.getName(), field.getInt(this));
        } else if (type == Long.TYPE) {
            cv.put(field.getName(), field.getLong(this));
        } else if (type == Short.TYPE) {
            cv.put(field.getName(), field.getShort(this));
        } else if (type.isEnum()) {
            final Object value = field.get(this);
            if (value != null) {
                final Method method = type.getMethod("name");
                final String str = (String) method.invoke(value);
                cv.put(field.getName(), str);
            }
        } else {
            // Try to JSONify it (db column must be of type text)
            final String json = mMapper.writeValueAsString(field.get(this));
            cv.put(field.getName(), json);
        }
    } catch (final IllegalAccessException e) {
        final String msg = String.format("Field %s is not accessible", type, field.getName());
        throw new IllegalArgumentException(msg);
    } catch (final JsonProcessingException e) {
        Ln.w(e, "Error while dumping %s of type %s to Json", field.getName(), type);
        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);
    } finally {
        field.setAccessible(wasAccessible);
    }
}

From source file:de.stklcode.jvault.connector.HTTPVaultConnectorOfflineTest.java

private Object getPrivate(Object target, String fieldName) {
    try {/* w w  w . j a  va 2s.co m*/
        Field field = target.getClass().getDeclaredField(fieldName);
        if (field.isAccessible())
            return field.get(target);
        field.setAccessible(true);
        Object value = field.get(target);
        field.setAccessible(false);
        return value;
    } catch (NoSuchFieldException | IllegalAccessException e) {
        return null;
    }
}

From source file:com.impetus.kundera.tests.crossdatastore.useraddress.AssociationBase.java

/**
 * /*ww w.  ja v  a2  s .  c o m*/
 */
private void truncateMongo() {
    Map<String, Client> clients = (Map<String, Client>) em.getDelegate();
    MongoDBClient client = (MongoDBClient) clients.get("addMongo");
    if (client != null) {
        try {
            Field db = client.getClass().getDeclaredField("mongoDb");
            if (!db.isAccessible()) {
                db.setAccessible(true);
            }
            DB mongoDB = (DB) db.get(client);
            if (mongoDB.collectionExists(colFamilies[0])) {
                mongoDB.getCollection(colFamilies[0]).drop();
            }
            if (mongoDB.collectionExists(colFamilies[1])) {
                mongoDB.getCollection(colFamilies[1]).drop();
            }
            if (colFamilies.length == 3 && mongoDB.collectionExists(colFamilies[2])) {
                mongoDB.getCollection(colFamilies[2]).drop();
            }
        } catch (SecurityException e) {
            log.error("Error while truncating db", e);
        } catch (NoSuchFieldException e) {
            log.error("Error while truncating db", e);
        } catch (IllegalArgumentException e) {
            log.error("Error while truncating db", e);
        } catch (IllegalAccessException e) {
            log.error("Error while truncating db", e);
        }
    }

}

From source file:de.digiway.rapidbreeze.server.infrastructure.objectstorage.ObjectStorage.java

private <T> T loadInstance(Class<T> clazz, Map<String, String> properties) {
    try {//from   w  w w . j  a va 2  s. co  m
        // Create new object of class using default constructor:
        Constructor<T> constructor = clazz.getDeclaredConstructor();
        if (!constructor.isAccessible()) {
            constructor.setAccessible(true);
        }
        T instance = constructor.newInstance();

        // Iterate over all existing properties and fill fields of new object:
        for (Map.Entry<String, String> entrySet : properties.entrySet()) {
            for (Field field : clazz.getDeclaredFields()) {
                if (field.getName().equals(entrySet.getKey())) {
                    if (!field.isAccessible()) {
                        field.setAccessible(true);
                    }
                    field.set(instance, stringToObject(field.getType(), entrySet.getValue()));
                    break;
                }
            }
        }
        return instance;
    } catch (NoSuchMethodException ex) {
        throw new IllegalStateException("Cannot find default constructor of class " + clazz, ex);
    } catch (SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException
            | InvocationTargetException ex) {
        throw new IllegalStateException("Error during value assignment.", ex);
    }
}

From source file:de.stklcode.jvault.connector.HTTPVaultConnectorOfflineTest.java

private void setPrivate(Object target, String fieldName, Object value) {
    try {//from  w  w w .  j a va2s  .  c o m
        Field field = target.getClass().getDeclaredField(fieldName);
        boolean accessible = field.isAccessible();
        field.setAccessible(true);
        field.set(target, value);
        field.setAccessible(accessible);
    } catch (NoSuchFieldException | IllegalAccessException e) {
        // Should not occur, to be taken care of in test code.
    }
}

From source file:org.bremersee.comparator.ObjectComparatorImpl.java

@Override
public int compare(Object o1, Object o2) {

    final boolean asc = getComparatorItem() != null ? getComparatorItem().isAsc() : true;
    final boolean ignoreCase = getComparatorItem() != null ? getComparatorItem().isIgnoreCase() : true;
    final boolean nullIsFirst = getComparatorItem() != null ? getComparatorItem().isNullIsFirst() : false;

    if (o1 == null && o2 == null) {
        return 0;
    }// ww  w  .j  a v a 2  s  . c  om
    if (o1 == null && o2 != null) {
        if (asc) {
            return nullIsFirst ? -1 : 1;
        } else {
            return nullIsFirst ? 1 : -1;
        }
    }
    if (o1 != null && o2 == null) {
        if (asc) {
            return nullIsFirst ? 1 : -1;
        } else {
            return nullIsFirst ? -1 : 1;
        }
    }

    if (getComparatorItem() == null || StringUtils.isBlank(getComparatorItem().getField())) {
        if (asc && o1 instanceof Comparable) {
            if (ignoreCase && o1 instanceof String && o2 instanceof String) {
                return ((String) o1).compareToIgnoreCase((String) o2);
            }
            return ((Comparable) o1).compareTo(o2);

        } else if (!asc && o2 instanceof Comparable) {

            if (ignoreCase && o1 instanceof String && o2 instanceof String) {
                return ((String) o2).compareToIgnoreCase((String) o1);
            }
            return ((Comparable) o2).compareTo(o1);

        } else {
            return 0;
        }
    }

    Object v1 = o1;
    Object v2 = o2;

    // supports fields like: fieldName1.fieldName2.fieldName3
    String[] fieldNames = getComparatorItem().getField().split(Pattern.quote("."));
    for (String fieldName : fieldNames) {

        if (StringUtils.isNotBlank(fieldName) && v1 != null && v2 != null) {

            Field f1 = findField(v1.getClass(), fieldName.trim());
            Field f2 = findField(v2.getClass(), fieldName.trim());

            if (f1 != null && f2 != null) {

                if (!f1.isAccessible()) {
                    f1.setAccessible(true);
                }
                if (!f2.isAccessible()) {
                    f2.setAccessible(true);
                }
                try {
                    v1 = f1.get(v1);
                } catch (IllegalArgumentException e) {
                    throw e;
                } catch (IllegalAccessException e) {
                    throw new ObjectComparatorException(e);
                }
                try {
                    v2 = f2.get(v2);
                } catch (IllegalArgumentException e) {
                    throw e;
                } catch (IllegalAccessException e) {
                    throw new ObjectComparatorException(e);
                }

            } else {

                Method m1 = null;
                Method m2 = null;
                String[] methodNames = getPossibleMethodNames(fieldName.trim());
                for (String methodName : methodNames) {
                    m1 = findMethod(v1.getClass(), methodName);
                    m2 = findMethod(v2.getClass(), methodName);
                    if (m1 != null && m2 != null) {
                        break;
                    }
                }
                if (m1 == null) {
                    return new ObjectComparatorImpl(getComparatorItem().getNextComparatorItem()).compare(v1,
                            v2);
                }

                if (m2 == null) {
                    return new ObjectComparatorImpl(getComparatorItem().getNextComparatorItem()).compare(v1,
                            v2);
                }

                if (!m1.isAccessible()) {
                    m1.setAccessible(true);
                }
                if (!m2.isAccessible()) {
                    m2.setAccessible(true);
                }

                try {
                    v1 = m1.invoke(v1);
                } catch (IllegalAccessException e) {
                    throw new ObjectComparatorException(e);
                } catch (IllegalArgumentException e) {
                    throw e;
                } catch (InvocationTargetException e) {
                    throw new ObjectComparatorException(e);
                }
                try {
                    v2 = m2.invoke(v2);
                } catch (IllegalAccessException e) {
                    throw new ObjectComparatorException(e);
                } catch (IllegalArgumentException e) {
                    throw e;
                } catch (InvocationTargetException e) {
                    throw new ObjectComparatorException(e);
                }
            }
        }
    }

    int result = new ObjectComparatorImpl(new ComparatorItem(null, asc, ignoreCase, nullIsFirst)).compare(v1,
            v2);

    if (result != 0) {
        return result;
    }

    return new ObjectComparatorImpl(getComparatorItem().getNextComparatorItem()).compare(o1, o2);
}