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.kuali.rice.core.api.mo.AbstractDataTransferObject.java

/**
 * Looks for a field named "_futureElements" on the class and clears it's value if it exists.  This allows us to
 * prevent from storing these values during serialization.
 *//*w  ww .j av a 2s  .  co m*/
private void clearFutureElements() {
    try {
        Field futureElementsField = getClass().getDeclaredField(CoreConstants.CommonElements.FUTURE_ELEMENTS);
        boolean originalAccessible = futureElementsField.isAccessible();
        futureElementsField.setAccessible(true);
        try {
            futureElementsField.set(this, null);
        } finally {
            futureElementsField.setAccessible(originalAccessible);
        }
    } catch (NoSuchFieldException e) {
        // if the field does not exist, don't do anything
    } catch (IllegalAccessException e) {
        // can't modify the field, ignore
    }
}

From source file:org.echocat.redprecursor.annotations.utils.AccessAlsoProtectedMembersReflectivePropertyAccessor.java

@Override
protected Field findField(String name, Class<?> clazz, boolean mustBeStatic) {
    Field result = null;//from   w w  w  .  j a v a 2 s  .  co m
    Class<?> current = clazz;
    while (result == null && !Object.class.equals(current)) {
        try {
            final Field potentialField = current.getDeclaredField(name);
            if (!mustBeStatic || Modifier.isStatic(potentialField.getModifiers())) {
                if (!potentialField.isAccessible()) {
                    potentialField.setAccessible(true);
                }
                result = potentialField;
            }
        } catch (NoSuchFieldException ignored) {
        }
        current = current.getSuperclass();
    }
    return result;
}

From source file:eu.vital.vitalcep.cep.CepProcess.java

private int getPid(Process process) {
    try {/*from www  .j a  v a2s .co m*/

        Class<?> cProcessImpl = process.getClass();
        java.lang.reflect.Field fPid = cProcessImpl.getDeclaredField("pid");

        if (!fPid.isAccessible()) {
            fPid.setAccessible(true);
        } else {
            return -1;
        }

        return fPid.getInt(process);
    } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {
        return -2;
    }
}

From source file:org.openinfinity.core.aspect.ArgumentBuilder.java

/**
 * Executes field callbacks on found and defined attribute names.
 * /*from ww w. j  a v  a2  s .com*/
 * @param argumentGatheringCallback Represents the actual callback method.
 * @param arguments Represents the arguments for method.
 * @param allowedFields Represents the allowed argument's field names.
 */
public void executeArgumentGatheringCallbackBasedOnDefinedFields(
        ArgumentGatheringFieldCallback<Field, Object> argumentGatheringCallback, Object[] arguments,
        String[] allowedFields) {
    for (String allowedField : allowedFields) {
        for (Object object : arguments) {
            try {
                JXPathContext context = JXPathContext.newContext(object);
                Object value = context.getValue(allowedField);
                String argument = object == null ? "null argument" : object.getClass().getName();
                generateKeyValueString(builder, object, value, argument);
                Field field = getField(allowedField, object, argument);
                if (!field.isAccessible()) {
                    field.setAccessible(true);
                }
                argumentGatheringCallback.onField(field, object);
            } catch (Throwable throwable) {
                LOGGER.warn(ExceptionUtil.getStackTraceString(throwable));
            }
        }
    }
}

From source file:com.hc.wx.server.common.bytecode.ReflectUtils.java

private static Object getEmptyObject(Class<?> returnType, Map<Class<?>, Object> emptyInstances, int level) {
    if (level > 2)
        return null;
    if (returnType == null) {
        return null;
    } else if (returnType == boolean.class || returnType == Boolean.class) {
        return false;
    } else if (returnType == char.class || returnType == Character.class) {
        return '\0';
    } else if (returnType == byte.class || returnType == Byte.class) {
        return (byte) 0;
    } else if (returnType == short.class || returnType == Short.class) {
        return (short) 0;
    } else if (returnType == int.class || returnType == Integer.class) {
        return 0;
    } else if (returnType == long.class || returnType == Long.class) {
        return 0L;
    } else if (returnType == float.class || returnType == Float.class) {
        return 0F;
    } else if (returnType == double.class || returnType == Double.class) {
        return 0D;
    } else if (returnType.isArray()) {
        return Array.newInstance(returnType.getComponentType(), 0);
    } else if (returnType.isAssignableFrom(ArrayList.class)) {
        return new ArrayList<Object>(0);
    } else if (returnType.isAssignableFrom(HashSet.class)) {
        return new HashSet<Object>(0);
    } else if (returnType.isAssignableFrom(HashMap.class)) {
        return new HashMap<Object, Object>(0);
    } else if (String.class.equals(returnType)) {
        return "";
    } else if (!returnType.isInterface()) {
        try {//ww  w . ja v a2  s  .  co  m
            Object value = emptyInstances.get(returnType);
            if (value == null) {
                value = returnType.newInstance();
                emptyInstances.put(returnType, value);
            }
            Class<?> cls = value.getClass();
            while (cls != null && cls != Object.class) {
                Field[] fields = cls.getDeclaredFields();
                for (Field field : fields) {
                    Object property = getEmptyObject(field.getType(), emptyInstances, level + 1);
                    if (property != null) {
                        try {
                            if (!field.isAccessible()) {
                                field.setAccessible(true);
                            }
                            field.set(value, property);
                        } catch (Throwable e) {
                        }
                    }
                }
                cls = cls.getSuperclass();
            }
            return value;
        } catch (Throwable e) {
            return null;
        }
    } else {
        return null;
    }
}

From source file:org.openinfinity.core.aspect.ArgumentBuilder.java

private void doRecursiveFieldLookUpAndCallFieldCallback(
        final ArgumentGatheringFieldCallback<Field, Object> argumentGatheringCallback, final Object[] objects) {
    for (final Object object : objects) {
        try {/*  w ww . j av  a 2s . c o  m*/
            if (object != null) {
                ReflectionUtils.doWithFields(object.getClass(), new FieldCallback() {
                    public void doWith(Field field) {
                        try {
                            if (!field.isAccessible()) {
                                field.setAccessible(Boolean.TRUE);
                            }
                            if (!(Modifier.isStatic(field.getModifiers())
                                    || Modifier.isFinal(field.getModifiers()))) {
                                argumentGatheringCallback.onField(field, object);
                                LOGGER.debug("Accessing field: " + field.getName());
                            }
                        } catch (Throwable e) {
                            LOGGER.error("Failure occurred while accessing object field.", e);
                        }
                    }
                });
            }
        } catch (Throwable throwable) {
            throw new SystemException(throwable);
        }
    }
}

From source file:fi.kela.kanta.util.GenericToString.java

private void addObjectInfo(StringBuilder sb, Field field, Object originalObject)
        throws IllegalArgumentException, IllegalAccessException {

    if (field != null) {
        if (!field.isAccessible()) {
            field.setAccessible(true);/*from  w  w w .jav a2s. c  om*/
        }
        if (field.getType().isAssignableFrom(Date.class)) {
            try {
                Object date = field.get(originalObject);
                if (date != null) {
                    sb.append(SDF.format(date));
                } else {
                    sb.append(GenericToString.null_date);
                }
                // Return accessibility?
            } catch (Exception e) {
                LOGGER.warn(e);
                sb.append(GenericToString.na_date);
            }
        } else {
            // TODO: Voi jatkokehitt siten ett tulostaa esim. lapsiobjektin tiedot
            Object fieldValue = field.get(originalObject);
            if (fieldValue != null) {
                sb.append(GenericToString.na_non_primitive);
            } else {
                sb.append(GenericToString.null_non_primitive);
            }
        }
    }
}

From source file:org.mayocat.search.elasticsearch.AbstractGenericEntityIndexDocumentPurveyor.java

protected Map<String, Object> extractSourceFromEntity(Entity entity, Tenant tenant) {
    Map<String, Object> source = Maps.newHashMap();
    Map<String, Object> properties = Maps.newHashMap();

    boolean hasClassLevelIndexAnnotation = entity.getClass().isAnnotationPresent(Index.class);

    for (Field field : entity.getClass().getDeclaredFields()) {
        boolean isAccessible = field.isAccessible();
        try {//from   w  w  w  .ja v a  2  s. com
            if (Modifier.isStatic(field.getModifiers())) {
                // we're not interested in static fields like serialVersionUid (or any other static field)
                continue;
            }

            if (Identifiable.class.isAssignableFrom(entity.getClass()) && field.getName().equals("id")) {
                // do not index the id of identifiable under properties
                continue;
            }

            if (Slug.class.isAssignableFrom(entity.getClass()) && field.getName().equals("slug")) {
                // do not index the slug of slugs under properties
                // (it is indexed as a top level property)
                continue;
            }

            field.setAccessible(true);
            boolean searchIgnoreFlag = field.isAnnotationPresent(DoNotIndex.class);
            boolean indexFlag = field.isAnnotationPresent(Index.class);

            if ((hasClassLevelIndexAnnotation || indexFlag) && !searchIgnoreFlag) {
                if (field.get(entity) != null) {
                    Class fieldClass = field.get(entity).getClass();

                    if (isAddonField(fieldClass, field)) {

                        // Treat addons differently.
                        // They're not located in the "properties" object like the other entity properties,
                        // but they're stored in their own "addon" object

                        Association<Map<String, AddonGroup>> addons = (Association<Map<String, AddonGroup>>) field
                                .get(entity);
                        if (addons.isLoaded()) {
                            source.put("addons", extractAddons(addons.get()));
                        }
                    } else if (BigDecimal.class.isAssignableFrom(fieldClass)) {

                        // Convert big decimal to double value

                        properties.put(field.getName(), ((BigDecimal) field.get(entity)).doubleValue());
                    } else {

                        // General case o>

                        properties.put(field.getName(), field.get(entity));
                    }
                } else {
                    properties.put(field.getName(), null);
                }
            }
        } catch (IllegalAccessException e) {
            this.logger.error("Error extracting entity", entity.getSlug(), e);
        } catch (JsonMappingException e) {
            this.logger.error("Error extracting entity", entity.getSlug(), e);
        } catch (JsonParseException e) {
            this.logger.error("Error extracting entity", entity.getSlug(), e);
        } catch (JsonProcessingException e) {
            this.logger.error("Error extracting entity", entity.getSlug(), e);
        } catch (IOException e) {
            this.logger.error("Error extracting entity", entity.getSlug(), e);
        } finally {
            field.setAccessible(isAccessible);
        }
    }

    source.put("properties", properties);

    if (HasFeaturedImage.class.isAssignableFrom(entity.getClass())) {
        HasFeaturedImage hasFeaturedImage = (HasFeaturedImage) entity;
        if (hasFeaturedImage.getFeaturedImageId() != null) {
            Attachment attachment = attachmentStore.findAndLoadById(hasFeaturedImage.getFeaturedImageId());
            if (attachment != null) {
                Map<String, Object> imageMap = Maps.newHashMap();
                imageMap.put("url", entityURLFactory.create(attachment, tenant));
                imageMap.put("title", attachment.getTitle());
                imageMap.put("extension", attachment.getExtension());
                source.put("featuredImage", imageMap);
            }
        }
    }

    source.put("url", entityURLFactory.create(entity, tenant).toString());
    source.put("api_url", entityURLFactory.create(entity, tenant, URLType.API).toString());
    source.put("slug", entity.getSlug());

    return source;
}

From source file:org.openinfinity.core.aspect.CryptoAspect.java

private void injectField(Field field, Object object, String textValue) {
    try {/*from w w  w  .j  av  a 2 s .c  o  m*/
        if (!field.isAccessible()) {
            field.setAccessible(Boolean.TRUE);
        }
        LOGGER.debug("Setting encrypted field [" + field.getName() + "], bytes [" + textValue + "]");
        field.set(object, textValue);
    } catch (Throwable throwable) {
        LOGGER.error("Error occurred while setting bytes to field: " + throwable.getMessage(), throwable);
    }
}

From source file:com.netflix.genie.agent.execution.services.impl.LaunchJobServiceImpl.java

private long getPid(final Process process) {
    long pid = -1;
    final String processClassName = process.getClass().getCanonicalName();
    try {/* w  w w.ja  va 2  s  . c  om*/
        if ("java.lang.UNIXProcess".equals(processClassName)) {
            final Field pidMemberField = process.getClass().getDeclaredField("pid");
            final boolean resetAccessible = pidMemberField.isAccessible();
            pidMemberField.setAccessible(true);
            pid = pidMemberField.getLong(process);
            pidMemberField.setAccessible(resetAccessible);
        } else {
            log.debug("Don't know how to access PID for class {}", processClassName);
        }
    } catch (final Throwable t) {
        log.warn("Failed to determine job process PID");
    }
    return pid;
}