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:edu.utah.further.core.xml.jaxb.ToParameterMapJaxbBuilder.java

/**
 * Append all properties of the object to the parameter map using reflection.
 * //from   w  w  w.jav  a  2  s  .  c  o m
 * @param namePrefix
 *            string to prefix object parameter name with
 * @param obj
 *            object to serialize
 */
private void appendAllFieldsUsingReflection(final String namePrefix, final Object obj) {
    final Class<?> clazz = obj.getClass();
    final Field[] fields = clazz.getDeclaredFields();
    AccessibleObject.setAccessible(fields, true);
    final String parentPrefix = isBlank(namePrefix) ? EMPTY_STRING : (namePrefix + PROPERTY_SCOPE_CHAR);
    try {
        for (final Field field : fields) {
            final Object fieldValue = field.get(obj);
            final XmlElement xmlElement = field.getAnnotation(XmlElement.class);
            if (xmlElement != null) {
                // Add field to map with a proper parameter name
                // final String xmlName = xmlElement.name();
                // final String propertyName = (xmlName == null) ? field.getName()
                // : xmlName;

                // Important: for now, we ignore JAXB names and use the field names,
                // for consistency with Spring's data binder. In the future, if we
                // find an efficient way to alias property names (recursively, for the
                // whole object graph) in Spring, we can use the code commented above
                // so that the XML binding is taken from the JAXB annotation's "name"
                // attribute.
                final String propertyName = field.getName();
                appendFieldUsingReflection(parentPrefix + propertyName, fieldValue);
            }
        }
    } catch (final Throwable e) {
        throw new IllegalStateException("Could not serialize object into a parameter map", e);
    }
}

From source file:com.googlecode.ehcache.annotations.key.AbstractDeepCacheKeyGenerator.java

/**
 * Calls {@link #shouldReflect(Object)} to determine if the object needs to be reflected on to
 * generate a good key. If so {@link AccessibleObject#setAccessible(AccessibleObject[], boolean)} is
 * used to enable access to private, protected and default fields. Each non-transient, non-static field
 * has {@link #deepHashCode(Object, Object)} called on it.
 *///  w ww.j  ava2s . com
protected final void reflectionDeepHashCode(G generator, final Object element) {
    //Special objects which shouldn't be reflected on due to lack of interesting fields
    if (element instanceof Class<?>) {
        this.append(generator, element);
        return;
    }

    //Determine if the element should be reflected on
    if (!this.shouldReflect(element)) {
        this.append(generator, element);
        return;
    }

    //Accumulate the data that makes up the object being reflected on so it can be recursed on as a single grouping of data
    final List<Object> reflectiveObject = new LinkedList<Object>();

    //Write out the target class so that two classes with the same fields can't collide
    reflectiveObject.add(element.getClass());

    try {
        for (Class<?> targetClass = element.getClass(); targetClass != null; targetClass = targetClass
                .getSuperclass()) {
            final Field[] fields = targetClass.getDeclaredFields();
            AccessibleObject.setAccessible(fields, true);

            for (int i = 0; i < fields.length; i++) {
                final Field field = fields[i];
                final int modifiers = field.getModifiers();

                //Ignore static and transient fields
                if (!Modifier.isStatic(modifiers) && !Modifier.isTransient(modifiers)) {
                    final Object fieldValue = field.get(element);
                    reflectiveObject.add(fieldValue);
                }
            }
        }
    } catch (IllegalAccessException exception) {
        ReflectionUtils.handleReflectionException(exception);
    }

    this.deepHashCode(generator, reflectiveObject);
}

From source file:de.micromata.genome.util.strings.ReducedReflectionToStringBuilder.java

/**
 * Append fields in internal.//from w w  w  . j a  v  a2 s . c  o  m
 *
 * @param clazz the clazz
 * @return true, if successful
 */
protected boolean appendFieldsInInternal(Class<?> clazz) {

    registerObject(getObject());
    if (clazz.isArray()) {
        this.reflectionAppendArray(this.getObject());
        return false;
    }
    Field[] fields = clazz.getDeclaredFields();
    AccessibleObject.setAccessible(fields, true);
    for (int i = 0; i < fields.length; i++) {
        Field field = fields[i];
        String fieldName = field.getName();
        if (this.accept(field) == false) {
            continue;
        }

        try {
            // Warning: Field.get(Object) creates wrappers objects
            // for primitive types.
            Object fieldValue = this.getValue(field);
            if (isObjectRegistered(fieldValue) == true && field.getType().isPrimitive() == false) {
                this.getStringBuffer().append(fieldName).append("=");
                this.appendAsObjectToString(fieldValue);
                this.getStringBuffer().append(",");

            } else {
                this.append(fieldName, fieldValue);
            }
        } catch (IllegalAccessException ex) {
            // this can't happen. Would get a Security exception
            // instead
            // throw a runtime exception in case the impossible
            // happens.
            throw new InternalError("Unexpected IllegalAccessException: " + ex.getMessage());
        }
    }
    return true;
}

From source file:com.gwtcx.server.servlet.FileUploadServlet.java

@SuppressWarnings("rawtypes")
private Object createEntity(Class entity, Field[] fields, String[] nextLine) {

    Log.debug("createEntity()");

    try {/* www .j  av a2  s . co m*/
        Object object = entity.newInstance();

        for (Field field : fields) {
            Class type = field.getType();

            // ignore Static fields
            if (Modifier.isStatic(field.getModifiers())) {
                continue;
            }

            if (type.getSimpleName().equals("String")) {
                Integer index = fieldNames.get(field.getName());
                if (index != null) {
                    field.set(object, nextLine[index].trim());
                    Log.debug("Field name: " + field.getName() + " index[" + index + "] = " + nextLine[index]);
                }
            } else if (type.getSimpleName().equals("List")) {

                List<Object> list = new ArrayList<Object>();

                Field declaredField = object.getClass().getDeclaredField(field.getName());
                Type genericType = declaredField.getGenericType();

                if (genericType instanceof ParameterizedType) {
                    ParameterizedType pt = (ParameterizedType) genericType;
                    Type[] t = pt.getActualTypeArguments();

                    // e.g. "class au.com.uptick.serendipity.server.domain.Address"
                    String className = t[0].toString().substring(6);
                    Log.debug("className: " + className);

                    Class nestedEntity = Class.forName(className);
                    Field[] nestedFields = nestedEntity.getDeclaredFields();
                    AccessibleObject.setAccessible(nestedFields, true);

                    Object nestedObject = createNestedEntity(nestedEntity, nestedFields, nextLine);

                    if (nestedObject != null) {
                        list.add(nestedObject);
                        field.set(object, list);
                    }
                }
            }
        }

        // Log.debug(object.toString());

        return object;
    } catch (Exception e) {
        Log.error("Error encountered while creating entity", e);
    }

    return null;
}

From source file:net.sf.firemox.database.DatabaseFactory.java

/**
 * Initialize property configurations from the dbStream. Existing proxies are
 * also initialized.//from  w w w.  ja va  2 s  .com
 * <ul>
 * Structure of Stream : Data[size]
 * <li>properties[] [...]</li>
 * </ul>
 * 
 * @param dbStream
 *          the MDB file containing rules
 * @throws IOException
 *           error during the database configuration.
 */
public static void init(InputStream dbStream) throws IOException {
    String[] dataProxyNameOrders = Configuration.getString("database.dataOrder", "").split("\\|");
    String[] pictureProxyNameOrders = Configuration.getString("database.pictureOrder", "").split("\\|");
    int count = dbStream.read();
    propertiesCacheConfig = new HashMap<String, PropertyConfig>(count);
    while (count-- > 0) {
        PropertyConfig propertyConfig = PropertyConfigFactory.getPropertyConfig(dbStream);
        propertiesCacheConfig.put(propertyConfig.getName(), propertyConfig);
    }

    // list available proxies
    final File proxiesLocation = MToolKit.getTbsFile(IdConst.PROXIES_LOCATION);
    final File[] lproxies;
    if (proxiesLocation == null) {
        Log.warn("The proxy directory '" + MToolKit.getTbsFile(IdConst.PROXIES_LOCATION, false)
                + "' does not exist");
        lproxies = new File[0];
    } else {
        lproxies = proxiesLocation.listFiles(new FileFilterPlus("xml"));
    }
    dataProxies = new Proxy[lproxies.length];
    pictureProxies = new Proxy[lproxies.length];

    XmlTools.initHashMaps();

    // validate them and build 'Proxy' instances from XML
    for (int i = lproxies.length; i-- > 0;) {
        try {
            dataProxies[i] = new Proxy(lproxies[i]);
            pictureProxies[i] = dataProxies[i];
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // re-order proxies with the defined orders
    int index = 0;
    for (String dataProxyNameOrder : dataProxyNameOrders) {
        for (int j = 0; j < dataProxies.length; j++) {
            if (dataProxyNameOrder.equalsIgnoreCase(dataProxies[j].getXmlName())) {
                final Proxy oldProxy = dataProxies[index];
                dataProxies[index] = dataProxies[j];
                dataProxies[j] = oldProxy;
                index++;
                break;
            }
        }
    }
    index = 0;
    for (String pictureProxyNameOrder : pictureProxyNameOrders) {
        for (int j = 0; j < pictureProxies.length; j++) {
            if (pictureProxyNameOrder.equalsIgnoreCase(pictureProxies[j].getXmlName())) {
                final Proxy oldProxy = pictureProxies[index];
                pictureProxies[index] = pictureProxies[j];
                pictureProxies[j] = oldProxy;
                index++;
                break;
            }
        }
    }

    // Initialize source file accessibility
    try {
        sourceFile = FileImageSource.class.getDeclaredField("imagefile");
        sourceUrl = URLImageSource.class.getDeclaredField("url");
        AccessibleObject.setAccessible(new AccessibleObject[] { sourceFile }, true);
        AccessibleObject.setAccessible(new AccessibleObject[] { sourceUrl }, true);
    } catch (Exception e) {
        e.printStackTrace();
    }

    XmlTools.clean();
}

From source file:br.gov.jfrj.siga.ex.bl.ExBL.java

public static Object getImplementationDeep(Object o, Class clazz, HashSet<Objeto> set)
        throws Exception, IllegalAccessException {
    Field f[] = clazz.getDeclaredFields();
    AccessibleObject.setAccessible(f, true);

    for (int i = 0; i < f.length; i++) {
        final Object object = f[i].get(o);
        if (object instanceof ObjetoBase) {
            Objeto objeto = (Objeto) object;

            if (objeto instanceof HibernateProxy) {
                objeto = (Objeto) (((HibernateProxy) objeto).getHibernateLazyInitializer().getImplementation());
            }/*from  w  ww  .  ja  va  2s .  c o  m*/

            prune(objeto);

            if (!set.contains(objeto)) {
                set.add(objeto);
                objeto = (Objeto) getImplementationDeep(objeto, objeto.getClass(), set);
            }
            f[i].set(o, objeto);
        }
    }
    if (clazz.getSuperclass().getSuperclass() != null) {
        System.out.println("*** Classe: " + clazz.getName() + " - " + clazz.getSuperclass().getName());
        getImplementationDeep(o, clazz.getSuperclass(), set);
    }
    return o;
}

From source file:org.apache.beam.runners.apex.ApexYarnLauncher.java

private static void copyShallow(DAG from, DAG to) {
    checkArgument(from.getClass() == to.getClass(), "must be same class %s %s", from.getClass(), to.getClass());
    Field[] fields = from.getClass().getDeclaredFields();
    AccessibleObject.setAccessible(fields, true);
    for (int i = 0; i < fields.length; i++) {
        Field field = fields[i];/*from  w w  w .  j a v a2  s . c om*/
        if (!java.lang.reflect.Modifier.isStatic(field.getModifiers())) {
            try {
                field.set(to, field.get(from));
            } catch (IllegalArgumentException | IllegalAccessException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

From source file:org.apache.hadoop.hive.metastore.VerifyingObjectStore.java

private static void dumpObject(StringBuilder errorStr, String name, Object p, Class<?> c, int level)
        throws IllegalAccessException {
    String offsetStr = repeat("  ", level);
    if (p == null || c == String.class || c.isPrimitive() || ClassUtils.wrapperToPrimitive(c) != null) {
        errorStr.append(offsetStr).append(name + ": [" + p + "]\n");
    } else if (ClassUtils.isAssignable(c, Iterable.class)) {
        errorStr.append(offsetStr).append(name + " is an iterable\n");
        Iterator<?> i1 = ((Iterable<?>) p).iterator();
        int i = 0;
        while (i1.hasNext()) {
            Object o1 = i1.next();
            Class<?> t = o1 == null ? Object.class : o1.getClass(); // ...
            dumpObject(errorStr, name + "[" + (i++) + "]", o1, t, level + 1);
        }//from  www .j a v a2  s . c o  m
    } else if (c.isArray()) {
        int len = Array.getLength(p);
        Class<?> t = c.getComponentType();
        errorStr.append(offsetStr).append(name + " is an array\n");
        for (int i = 0; i < len; ++i) {
            dumpObject(errorStr, name + "[" + i + "]", Array.get(p, i), t, level + 1);
        }
    } else if (ClassUtils.isAssignable(c, Map.class)) {
        Map<?, ?> c1 = (Map<?, ?>) p;
        errorStr.append(offsetStr).append(name + " is a map\n");
        dumpObject(errorStr, name + ".keys", c1.keySet(), Set.class, level + 1);
        dumpObject(errorStr, name + ".vals", c1.values(), Collection.class, level + 1);
    } else {
        errorStr.append(offsetStr).append(name + " is of type " + c.getCanonicalName() + "\n");
        // TODO: this doesn't include superclass.
        Field[] fields = c.getDeclaredFields();
        AccessibleObject.setAccessible(fields, true);
        for (int i = 0; i < fields.length; i++) {
            Field f = fields[i];
            if (f.getName().indexOf('$') != -1 || Modifier.isStatic(f.getModifiers()))
                continue;
            dumpObject(errorStr, name + "." + f.getName(), f.get(p), f.getType(), level + 1);
        }
    }
}

From source file:org.apache.maven.plugin.testing.AbstractMojoTestCase.java

/**
 * Convenience method to obtain all variables and values from the mojo (including its superclasses)
 *
 * Note: the values in the map are of type Object so the caller is responsible for casting to desired types.
 *
 * @param clazz//from   ww w.  ja v  a2  s . co  m
 * @param object
 * @return map of variable names and values
 */
protected Map<String, Object> getVariablesAndValuesFromObject(Class<?> clazz, Object object)
        throws IllegalAccessException {
    Map<String, Object> map = new HashMap<String, Object>();

    Field[] fields = clazz.getDeclaredFields();

    AccessibleObject.setAccessible(fields, true);

    for (Field field : fields) {
        map.put(field.getName(), field.get(object));
    }

    Class<?> superclass = clazz.getSuperclass();

    if (!Object.class.equals(superclass)) {
        map.putAll(getVariablesAndValuesFromObject(superclass, object));
    }

    return map;
}

From source file:org.jtester.hamcrest.matcher.property.report.ObjectFormatter.java

/**
 * Formats the field values of the given object.
 * //from   ww w  .  ja  v  a  2s  .  co  m
 * @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
 */
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();
    }
}