Example usage for java.lang.reflect AccessibleObject setAccessible

List of usage examples for java.lang.reflect AccessibleObject setAccessible

Introduction

In this page you can find the example usage for java.lang.reflect AccessibleObject setAccessible.

Prototype

@CallerSensitive
public static void setAccessible(AccessibleObject[] array, boolean flag) 

Source Link

Document

Convenience method to set the accessible flag for an array of reflected objects with a single security check (for efficiency).

Usage

From source file:org.jtester.module.utils.ObjectFormatter.java

/**
 * Formats the field values of the given object.
 *
 * @param object       The object, not null
 * @param clazz        The class for which to format the fields, not null
 * @param currentDepth The current recursion depth
 * @param result       The builder to append the result to, not null
 *//*from  ww  w  . j  a  va2 s.  co  m*/
protected void formatFields(Object object, Class<?> clazz, int currentDepth, StringBuilder result) {
    Field[] fields = clazz.getDeclaredFields();
    AccessibleObject.setAccessible(fields, true);

    for (int i = 0; i < fields.length; i++) {
        // skip transient and static fields
        Field field = fields[i];
        if (isTransient(field.getModifiers()) || isStatic(field.getModifiers()) || field.isSynthetic()) {
            continue;
        }
        try {
            if (i > 0) {
                result.append(", ");
            }
            result.append(field.getName());
            result.append("=");
            formatImpl(field.get(object), currentDepth + 1, result);

        } catch (IllegalAccessException e) {
            // this can't happen. Would get a Security exception instead
            // throw a runtime exception in case the impossible happens.
            throw new InternalError("Unexpected IllegalAccessException");
        }
    }

    // format fields declared in superclass
    Class<?> superclazz = clazz.getSuperclass();
    while (superclazz != null && !superclazz.getName().startsWith("java.lang")) {
        formatFields(object, superclazz, currentDepth, result);
        superclazz = superclazz.getSuperclass();
    }
}

From source file:org.musicrecital.webapp.taglib.ConstantsTag.java

/**
 * Main method that does processing and exposes Constants in specified scope 
 * @return int//from  ww  w.  j a v  a 2 s.c om
 * @throws JspException if processing fails
 */
@Override
public int doStartTag() throws JspException {
    // Using reflection, get the available field names in the class
    Class c = null;
    int toScope = PageContext.PAGE_SCOPE;

    if (scope != null) {
        toScope = getScope(scope);
    }

    try {
        c = Class.forName(clazz);
    } catch (ClassNotFoundException cnf) {
        log.error("ClassNotFound - maybe a typo?");
        throw new JspException(cnf.getMessage());
    }

    try {
        // if var is null, expose all variables
        if (var == null) {
            Field[] fields = c.getDeclaredFields();

            AccessibleObject.setAccessible(fields, true);

            for (Field field : fields) {
                pageContext.setAttribute(field.getName(), field.get(this), toScope);
            }
        } else {
            try {
                Object value = c.getField(var).get(this);
                pageContext.setAttribute(c.getField(var).getName(), value, toScope);
            } catch (NoSuchFieldException nsf) {
                log.error(nsf.getMessage());
                throw new JspException(nsf);
            }
        }
    } catch (IllegalAccessException iae) {
        log.error("Illegal Access Exception - maybe a classloader issue?");
        throw new JspException(iae);
    }

    // Continue processing this page
    return (SKIP_BODY);
}

From source file:org.musicrecital.webapp.taglib.ConstantsTei.java

/**
 * Return information about the scripting variables to be created.
 * @param data the input data/* w w w.java 2  s  .c  o  m*/
 * @return VariableInfo array of variable information
 */
public VariableInfo[] getVariableInfo(TagData data) {
    // loop through and expose all attributes
    List<VariableInfo> vars = new ArrayList<VariableInfo>();

    try {
        String clazz = data.getAttributeString("className");

        if (clazz == null) {
            clazz = Constants.class.getName();
        }

        Class c = Class.forName(clazz);

        // if no var specified, get all
        if (data.getAttributeString("var") == null) {
            Field[] fields = c.getDeclaredFields();

            AccessibleObject.setAccessible(fields, true);

            for (Field field : fields) {
                String type = field.getType().getName();
                vars.add(new VariableInfo(field.getName(),
                        ((field.getType().isArray()) ? type.substring(2, type.length() - 1) + "[]" : type),
                        true, VariableInfo.AT_END));
            }
        } else {
            String var = data.getAttributeString("var");
            String type = c.getField(var).getType().getName();
            vars.add(new VariableInfo(c.getField(var).getName(),
                    ((c.getField(var).getType().isArray()) ? type.substring(2, type.length() - 1) + "[]"
                            : type),
                    true, VariableInfo.AT_END));
        }
    } catch (Exception cnf) {
        log.error(cnf.getMessage());
        cnf.printStackTrace();
    }

    return vars.toArray(new VariableInfo[] {});
}

From source file:org.openhie.openempi.webapp.taglib.ConstantsTag.java

/**
 * Main method that does processing and exposes Constants in specified scope 
 * @return int/*from   w ww  .  jav  a  2  s . c  o m*/
 * @throws JspException if processing fails
 */
@SuppressWarnings("unchecked")
@Override
public int doStartTag() throws JspException {
    // Using reflection, get the available field names in the class
    Class c = null;
    int toScope = PageContext.PAGE_SCOPE;

    if (scope != null) {
        toScope = getScope(scope);
    }

    try {
        c = Class.forName(clazz);
    } catch (ClassNotFoundException cnf) {
        log.error("ClassNotFound - maybe a typo?");
        throw new JspException(cnf.getMessage());
    }

    try {
        // if var is null, expose all variables
        if (var == null) {
            Field[] fields = c.getDeclaredFields();

            AccessibleObject.setAccessible(fields, true);

            for (Field field : fields) {
                pageContext.setAttribute(field.getName(), field.get(this), toScope);
            }
        } else {
            try {
                Object value = c.getField(var).get(this);
                pageContext.setAttribute(c.getField(var).getName(), value, toScope);
            } catch (NoSuchFieldException nsf) {
                log.error(nsf.getMessage());
                throw new JspException(nsf);
            }
        }
    } catch (IllegalAccessException iae) {
        log.error("Illegal Access Exception - maybe a classloader issue?");
        throw new JspException(iae);
    }

    // Continue processing this page
    return (SKIP_BODY);
}

From source file:org.openhie.openempi.webapp.taglib.ConstantsTei.java

/**
 * Return information about the scripting variables to be created.
 * @param data the input data//  ww w  . j  a  va  2s  . c o  m
 * @return VariableInfo array of variable information
 */
@SuppressWarnings("unchecked")
public VariableInfo[] getVariableInfo(TagData data) {
    // loop through and expose all attributes
    List<VariableInfo> vars = new ArrayList<VariableInfo>();

    try {
        String clazz = data.getAttributeString("className");

        if (clazz == null) {
            clazz = Constants.class.getName();
        }

        Class c = Class.forName(clazz);

        // if no var specified, get all
        if (data.getAttributeString("var") == null) {
            Field[] fields = c.getDeclaredFields();

            AccessibleObject.setAccessible(fields, true);

            for (Field field : fields) {
                String type = field.getType().getName();
                vars.add(new VariableInfo(field.getName(),
                        ((field.getType().isArray()) ? type.substring(2, type.length() - 1) + "[]" : type),
                        true, VariableInfo.AT_END));
            }
        } else {
            String var = data.getAttributeString("var");
            String type = c.getField(var).getType().getName();
            vars.add(new VariableInfo(c.getField(var).getName(),
                    ((c.getField(var).getType().isArray()) ? type.substring(2, type.length() - 1) + "[]"
                            : type),
                    true, VariableInfo.AT_END));
        }
    } catch (Exception cnf) {
        log.error(cnf.getMessage());
        cnf.printStackTrace();
    }

    return vars.toArray(new VariableInfo[] {});
}

From source file:org.projectforge.business.gantt.GanttChartDao.java

public GanttChartDao() {
    super(GanttChartDO.class);
    userRightId = USER_RIGHT_ID;/* w w  w  .j  a  v  a 2 s. c o m*/
    AccessibleObject.setAccessible(taskFields, true);
    fieldMapping = new HashMap<String, String>();
    fieldMapping.put("predecessor", "ganttPredecessor");
    fieldMapping.put("predecessorOffset", "ganttPredecessorOffset");
    fieldMapping.put("relationType", "ganttRelationType");
    fieldMapping.put("type", "ganttObjectType");
}

From source file:org.projectforge.business.user.UserPrefDao.java

private void addUserPrefParameters(final UserPrefDO userPref, final Class<?> beanType, final Object obj) {
    Validate.notNull(userPref);//from ww w . j  a va  2 s .  co  m
    Validate.notNull(beanType);
    final Field[] fields = beanType.getDeclaredFields();
    AccessibleObject.setAccessible(fields, true);
    int no = 0;
    for (final Field field : fields) {
        if (field.isAnnotationPresent(UserPrefParameter.class) == true) {
            final UserPrefEntryDO userPrefEntry = new UserPrefEntryDO();
            userPrefEntry.setParameter(field.getName());
            if (obj != null) {
                Object value = null;
                try {
                    value = field.get(obj);
                    userPrefEntry.setValue(convertParameterValueToString(value));
                } catch (final IllegalAccessException ex) {
                    log.error(ex.getMessage(), ex);
                }
                userPrefEntry.valueAsObject = value;
            }
            evaluateAnnotation(userPrefEntry, beanType, field);
            if (userPrefEntry.orderString == null) {
                userPrefEntry.orderString = "ZZZ" + StringHelper.format2DigitNumber(no++);
            }
            userPref.addUserPrefEntry(userPrefEntry);
        }
    }
}

From source file:org.projectforge.business.user.UserPrefDao.java

/**
 * Fill object fields from the parameters of the given userPref.
 * /*from  www .j ava 2s .  c o  m*/
 * @param userPref
 * @param obj
 * @param preserveExistingValues If true then existing value will not be overwritten by the user pref object. Default
 *          is false.
 * @see #addUserPrefParameters(UserPrefDO, Object)
 */
public void fillFromUserPrefParameters(final UserPrefDO userPref, final Object obj,
        final boolean preserveExistingValues) {
    Validate.notNull(userPref);
    Validate.notNull(obj);
    final Field[] fields = obj.getClass().getDeclaredFields();
    AccessibleObject.setAccessible(fields, true);
    if (userPref.getUserPrefEntries() != null) {
        for (final UserPrefEntryDO entry : userPref.getUserPrefEntries()) {
            Field field = null;
            for (final Field f : fields) {
                if (f.getName().equals(entry.getParameter()) == true) {
                    field = f;
                    break;
                }
            }
            if (field == null) {
                log.error("Declared field '" + entry.getParameter() + "' not found for " + obj.getClass()
                        + ". Ignoring parameter.");
            } else {
                final Object value = getParameterValue(field.getType(), entry.getValue());
                try {
                    if (preserveExistingValues == true) {
                        final Object oldValue = field.get(obj);
                        if (oldValue != null) {
                            if (oldValue instanceof String) {
                                if (((String) oldValue).length() > 0) {
                                    // Preserve existing value:
                                    continue;
                                }
                            } else {
                                // Preserve existing value:
                                continue;
                            }
                        }
                    }
                    field.set(obj, value);
                } catch (final IllegalArgumentException ex) {
                    log.error(ex.getMessage() + " While setting declared field '" + entry.getParameter()
                            + "' of " + obj.getClass() + ". Ignoring parameter.", ex);
                } catch (final IllegalAccessException ex) {
                    log.error(ex.getMessage() + " While setting declared field '" + entry.getParameter()
                            + "' of " + obj.getClass() + ". Ignoring parameter.", ex);
                }
            }
        }
    }
}

From source file:org.projectforge.core.AbstractBaseDO.java

/**
 * //from   w  w w .j a  va2 s.c o m
 * @param srcClazz
 * @param src
 * @param dest
 * @param ignoreFields
 * @return true, if any modifications are detected, otherwise false;
 */
@SuppressWarnings("unchecked")
private static ModificationStatus copyDeclaredFields(final Class<?> srcClazz, final BaseDO<?> src,
        final BaseDO<?> dest, final String... ignoreFields) {
    final Field[] fields = srcClazz.getDeclaredFields();
    AccessibleObject.setAccessible(fields, true);
    ModificationStatus modificationStatus = null;
    for (final Field field : fields) {
        final String fieldName = field.getName();
        if ((ignoreFields != null && ArrayUtils.contains(ignoreFields, fieldName) == true)
                || accept(field) == false) {
            continue;
        }
        try {
            final Object srcFieldValue = field.get(src);
            final Object destFieldValue = field.get(dest);
            if (field.getType().isPrimitive() == true) {
                if (ObjectUtils.equals(destFieldValue, srcFieldValue) == false) {
                    field.set(dest, srcFieldValue);
                    modificationStatus = getModificationStatus(modificationStatus, src, fieldName);
                }
                continue;
            } else if (srcFieldValue == null) {
                if (field.getType() == String.class) {
                    if (StringUtils.isNotEmpty((String) destFieldValue) == true) {
                        field.set(dest, null);
                        modificationStatus = getModificationStatus(modificationStatus, src, fieldName);
                    }
                } else if (destFieldValue != null) {
                    field.set(dest, null);
                    modificationStatus = getModificationStatus(modificationStatus, src, fieldName);
                } else {
                    // dest was already null
                }
            } else if (srcFieldValue instanceof Collection) {
                Collection<Object> destColl = (Collection<Object>) destFieldValue;
                final Collection<Object> srcColl = (Collection<Object>) srcFieldValue;
                final Collection<Object> toRemove = new ArrayList<Object>();
                if (srcColl != null && destColl == null) {
                    if (srcColl instanceof TreeSet) {
                        destColl = new TreeSet<Object>();
                    } else if (srcColl instanceof HashSet) {
                        destColl = new HashSet<Object>();
                    } else if (srcColl instanceof List) {
                        destColl = new ArrayList<Object>();
                    } else if (srcColl instanceof PersistentSet) {
                        destColl = new HashSet<Object>();
                    } else {
                        log.error("Unsupported collection type: " + srcColl.getClass().getName());
                    }
                    field.set(dest, destColl);
                }
                for (final Object o : destColl) {
                    if (srcColl.contains(o) == false) {
                        toRemove.add(o);
                    }
                }
                for (final Object o : toRemove) {
                    if (log.isDebugEnabled() == true) {
                        log.debug("Removing collection entry: " + o);
                    }
                    destColl.remove(o);
                    modificationStatus = getModificationStatus(modificationStatus, src, fieldName);
                }
                for (final Object srcEntry : srcColl) {
                    if (destColl.contains(srcEntry) == false) {
                        if (log.isDebugEnabled() == true) {
                            log.debug("Adding new collection entry: " + srcEntry);
                        }
                        destColl.add(srcEntry);
                        modificationStatus = getModificationStatus(modificationStatus, src, fieldName);
                    } else if (srcEntry instanceof BaseDO) {
                        final PFPersistancyBehavior behavior = field.getAnnotation(PFPersistancyBehavior.class);
                        if (behavior != null && behavior.autoUpdateCollectionEntries() == true) {
                            BaseDO<?> destEntry = null;
                            for (final Object entry : destColl) {
                                if (entry.equals(srcEntry) == true) {
                                    destEntry = (BaseDO<?>) entry;
                                    break;
                                }
                            }
                            Validate.notNull(destEntry);
                            final ModificationStatus st = destEntry.copyValuesFrom((BaseDO<?>) srcEntry);
                            modificationStatus = getModificationStatus(modificationStatus, st);
                        }
                    }
                }
            } else if (srcFieldValue instanceof BaseDO) {
                final Serializable srcFieldValueId = HibernateUtils.getIdentifier((BaseDO<?>) srcFieldValue);
                if (srcFieldValueId != null) {
                    if (destFieldValue == null || ObjectUtils.equals(srcFieldValueId,
                            ((BaseDO<?>) destFieldValue).getId()) == false) {
                        field.set(dest, srcFieldValue);
                        modificationStatus = getModificationStatus(modificationStatus, src, fieldName);
                    }
                } else {
                    log.error(
                            "Can't get id though can't copy the BaseDO (see error message above about HHH-3502).");
                }
            } else if (srcFieldValue instanceof java.sql.Date) {
                if (destFieldValue == null) {
                    field.set(dest, srcFieldValue);
                    modificationStatus = getModificationStatus(modificationStatus, src, fieldName);
                } else {
                    final DayHolder srcDay = new DayHolder((Date) srcFieldValue);
                    final DayHolder destDay = new DayHolder((Date) destFieldValue);
                    if (srcDay.isSameDay(destDay) == false) {
                        field.set(dest, srcDay.getSQLDate());
                        modificationStatus = getModificationStatus(modificationStatus, src, fieldName);
                    }
                }
            } else if (srcFieldValue instanceof Date) {
                if (destFieldValue == null
                        || ((Date) srcFieldValue).getTime() != ((Date) destFieldValue).getTime()) {
                    field.set(dest, srcFieldValue);
                    modificationStatus = getModificationStatus(modificationStatus, src, fieldName);
                }
            } else if (srcFieldValue instanceof BigDecimal) {
                if (destFieldValue == null
                        || ((BigDecimal) srcFieldValue).compareTo((BigDecimal) destFieldValue) != 0) {
                    field.set(dest, srcFieldValue);
                    modificationStatus = getModificationStatus(modificationStatus, src, fieldName);
                }
            } else if (ObjectUtils.equals(destFieldValue, srcFieldValue) == false) {
                field.set(dest, srcFieldValue);
                modificationStatus = getModificationStatus(modificationStatus, src, fieldName);
            }
        } catch (final IllegalAccessException ex) {
            throw new InternalError("Unexpected IllegalAccessException: " + ex.getMessage());
        }
    }
    final Class<?> superClazz = srcClazz.getSuperclass();
    if (superClazz != null) {
        final ModificationStatus st = copyDeclaredFields(superClazz, src, dest, ignoreFields);
        modificationStatus = getModificationStatus(modificationStatus, st);
    }
    return modificationStatus;
}

From source file:org.projectforge.core.ConfigXml.java

/**
 * Copies only not null values of the configuration.
 *//*from   ww w.  j a  v a  2  s.  c om*/
private static void copyDeclaredFields(final String prefix, final Class<?> srcClazz, final Object src,
        final Object dest, final String... ignoreFields) {
    final Field[] fields = srcClazz.getDeclaredFields();
    AccessibleObject.setAccessible(fields, true);
    for (final Field field : fields) {
        if (ignoreFields != null && ArrayUtils.contains(ignoreFields, field.getName()) == false
                && accept(field)) {
            try {
                final Object srcFieldValue = field.get(src);
                if (srcFieldValue == null) {
                    // Do nothing
                } else if (srcFieldValue instanceof ConfigurationData) {
                    final Object destFieldValue = field.get(dest);
                    Validate.notNull(destFieldValue);
                    final StringBuffer buf = new StringBuffer();
                    if (prefix != null) {
                        buf.append(prefix);
                    }
                    String alias = null;
                    if (field.isAnnotationPresent(XmlField.class)) {
                        final XmlField xmlFieldAnn = field.getAnnotation(XmlField.class);
                        if (xmlFieldAnn != null) {
                            alias = xmlFieldAnn.alias();
                        }
                    }
                    if (alias != null) {
                        buf.append(alias);
                    } else {
                        buf.append(field.getClass().getName());
                    }
                    buf.append(".");
                    copyDeclaredFields(buf.toString(), srcFieldValue.getClass(), srcFieldValue, destFieldValue,
                            ignoreFields);
                } else if (PLUGIN_CONFIGS_FIELD_NAME.equals(field.getName()) == true) {
                    // Do nothing.
                } else {
                    field.set(dest, srcFieldValue);
                    if (StringHelper.isIn(field.getName(), "receiveSmsKey", "phoneLookupKey") == true) {
                        log.info(StringUtils.defaultString(prefix) + field.getName() + " = ****");
                    } else {
                        log.info(StringUtils.defaultString(prefix) + field.getName() + " = " + srcFieldValue);
                    }
                }
            } catch (final IllegalAccessException ex) {
                throw new InternalError("Unexpected IllegalAccessException: " + ex.getMessage());
            }
        }
    }
    final Class<?> superClazz = srcClazz.getSuperclass();
    if (superClazz != null) {
        copyDeclaredFields(prefix, superClazz, src, dest, ignoreFields);
    }
}