Example usage for java.lang.reflect Field setAccessible

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

Introduction

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

Prototype

@Override
@CallerSensitive
public void setAccessible(boolean flag) 

Source Link

Usage

From source file:edu.mit.csail.sdg.alloy4.Terminal.java

static boolean getBoolean(Field f, Object obj) {
    f.setAccessible(true);

    try {/*from w w w. j a  v  a  2s .c  o m*/
        return (Boolean) f.get(obj);

    } catch (IllegalArgumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return false;
}

From source file:fr.paris.lutece.util.bean.BeanUtil.java

/**
 * Populate a bean using parameters in http request
 * /*from  w  w w.  j a  v  a  2  s.  c  o  m*/
 * @param bean bean to populate
 * @param request http request
 */
public static void populate(Object bean, HttpServletRequest request) {
    for (Field field : bean.getClass().getDeclaredFields()) {
        try {
            // for all boolean field, init to false
            if (field.getType().getName().equals(Boolean.class.getName())
                    || field.getType().getName().equals(boolean.class.getName())) {
                field.setAccessible(true);
                field.set(bean, false);
            }
        } catch (Exception e) {
            String error = "La valeur du champ " + field.getName() + " de la classe "
                    + bean.getClass().getName() + " n'a pas pu tre rcupr ";
            AppLogService.error(error);
            throw new RuntimeException(error, e);
        }
    }

    try {
        BeanUtils.populate(bean, convertMap(request.getParameterMap()));
    } catch (IllegalAccessException e) {
        AppLogService.error("Unable to fetch data from request", e);
    } catch (InvocationTargetException e) {
        AppLogService.error("Unable to fetch data from request", e);
    }
}

From source file:net.sf.eclipsecs.core.builder.CheckerFactory.java

private static void applyTreeWalkerCacheWorkaround(Checker checker) {
    try {/*from   w ww  .  j  av  a 2s. c o  m*/
        Field fileSetChecksField = Checker.class.getDeclaredField("mFileSetChecks");
        fileSetChecksField.setAccessible(true);

        @SuppressWarnings("unchecked")
        List<FileSetCheck> fileSetChecks = (List<FileSetCheck>) fileSetChecksField.get(checker);

        for (FileSetCheck fsc : fileSetChecks) {
            if (fsc instanceof TreeWalker) {
                TreeWalker tw = (TreeWalker) fsc;

                // only reset when we have a "default cache" without an actual configured cache file.
                Field cacheField = TreeWalker.class.getDeclaredField("mCache");
                cacheField.setAccessible(true);

                Object cache = cacheField.get(tw);

                Field detailsFileField = cache.getClass().getDeclaredField("mDetailsFile");
                detailsFileField.setAccessible(true);

                if (detailsFileField.get(cache) == null) {
                    tw.setCacheFile(null);
                }
            }
        }
    } catch (Exception e) {
        // Ah, what the heck, I tried. Now get out of my way.
    }
}

From source file:org.dawnsci.commandserver.core.process.ProgressableProcess.java

protected static int getPid(Process p) throws Exception {

    if (Platform.isWindows()) {
        Field f = p.getClass().getDeclaredField("handle");
        f.setAccessible(true);
        int pid = Kernel32.INSTANCE.GetProcessId((Long) f.get(p));
        return pid;

    } else if (Platform.isLinux()) {
        Field f = p.getClass().getDeclaredField("pid");
        f.setAccessible(true);// w  w  w .  j a  va2  s  .  c  om
        int pid = (Integer) f.get(p);
        return pid;

    } else {
        throw new Exception("Cannot currently process pid for " + System.getProperty("os.name"));
    }
}

From source file:com.taobao.android.builder.tools.guide.AtlasConfigHelper.java

public static void setProperty(Object object, String fieldName, String value)
        throws IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchFieldException {

    String[] fieldNames = fieldName.split("\\.");

    Object last = object;//from www  .  j  av a 2s  .com
    for (int i = 0; i < fieldNames.length - 1; i++) {

        String field = fieldNames[i];

        if (last instanceof NamedDomainObjectContainer) {
            last = ((NamedDomainObjectContainer) last).maybeCreate(field);
        } else {
            Field declaredField = last.getClass().getField(field);
            declaredField.setAccessible(true);

            if (null == declaredField.get(last)) {
                Object newInstance = declaredField.getType().getConstructors().getClass().newInstance();
                declaredField.set(last, newInstance);
            }

            last = declaredField.get(last);
        }
    }

    BeanUtils.setProperty(last, fieldNames[fieldNames.length - 1], value);
}

From source file:Main.java

/**
 * Set property(field) of the specified object.
 * @param bean The object which has the given property
 * @param field The field to be set/*from   www  .  j a  v  a  2  s  .c  o  m*/
 * @param value The value to be set to the field
 * @throws IllegalAccessException
 * @throws InvocationTargetException
 * @throws NoSuchMethodException
 */
public static void setProperty(Object bean, Field field, Object value)
        throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {

    if (bean == null || field == null) {
        return;
    }

    try {
        field.setAccessible(true);
        field.set(bean, value);
    } catch (Exception e) {
    }

}

From source file:cn.whereyougo.framework.utils.PackageManagerUtil.java

/**
 * ??,json//from  w w  w  . ja  v  a 2s . c om
 * 
 * @param ctx
 */
public static JSONObject collectDeviceInfo(Context ctx) {
    JSONObject result = new JSONObject();
    Field[] fields = Build.class.getDeclaredFields();
    for (Field field : fields) {
        try {
            field.setAccessible(true);
            result.put(field.getName(), field.get(null).toString());
        } catch (Exception e) {
            LogUtil.d(TAG, "an error occured when collect device info " + e.getMessage());
        }
    }

    return result;
}

From source file:edu.usu.sdl.openstorefront.core.util.EntityUtil.java

/**
 * This will set default on the fields that are marked with a default and
 * are null// w ww  .ja  v  a 2 s  . c  o m
 *
 * @param entity
 */
public static void setDefaultsOnFields(Object entity) {
    Objects.requireNonNull(entity, "Entity must not be NULL");
    List<Field> fields = getAllFields(entity.getClass());
    for (Field field : fields) {
        DefaultFieldValue defaultFieldValue = field.getAnnotation(DefaultFieldValue.class);
        if (defaultFieldValue != null) {
            field.setAccessible(true);
            try {
                if (field.get(entity) == null) {
                    String value = defaultFieldValue.value();
                    Class fieldClass = field.getType();
                    if (fieldClass.getSimpleName().equalsIgnoreCase(String.class.getSimpleName())) {
                        field.set(entity, value);
                    } else if (fieldClass.getSimpleName().equalsIgnoreCase(Long.class.getSimpleName())) {
                        field.set(entity, value);
                    } else if (fieldClass.getSimpleName().equalsIgnoreCase(Integer.class.getSimpleName())) {
                        field.set(entity, Integer.parseInt(value));
                    } else if (fieldClass.getSimpleName().equalsIgnoreCase(Boolean.class.getSimpleName())) {
                        field.set(entity, Convert.toBoolean(value));
                    } else if (fieldClass.getSimpleName().equalsIgnoreCase(Double.class.getSimpleName())) {
                        field.set(entity, Double.parseDouble(value));
                    } else if (fieldClass.getSimpleName().equalsIgnoreCase(Float.class.getSimpleName())) {
                        field.set(entity, Float.parseFloat(value));
                    } else if (fieldClass.getSimpleName().equalsIgnoreCase(BigDecimal.class.getSimpleName())) {
                        field.set(entity, Convert.toBigDecimal(value));
                    } else if (fieldClass.getSimpleName().equalsIgnoreCase(Date.class.getSimpleName())) {
                        field.set(entity, TimeUtil.fromString(value));
                    } else if (fieldClass.getSimpleName().equalsIgnoreCase(BigInteger.class.getSimpleName())) {
                        field.set(entity, new BigInteger(value));
                    }
                }
            } catch (IllegalArgumentException | IllegalAccessException ex) {
                throw new OpenStorefrontRuntimeException(
                        "Unable to get value on " + entity.getClass().getName(), "Check entity passed in.");
            }
        }
    }
}

From source file:com.taobao.android.builder.tools.guide.AtlasConfigHelper.java

private static void readConfig(Object object, String prefix, List<AtlasConfigField> configFieldList,
        int groupOrder, String variantName) throws IllegalAccessException {

    if (null == object) {
        return;/*from   w w w  .j  a  va2s. c o  m*/
    }

    for (Field field : getAllFields(object.getClass())) {

        field.setAccessible(true);

        Config config = field.getAnnotation(Config.class);
        if (null != config) {
            AtlasConfigField configField = new AtlasConfigField();
            configField.name = prefix + "." + field.getName();
            configField.order = config.order();
            configField.desc = config.message();
            Object obj = field.get(object);
            configField.value = (null == obj ? null : String.valueOf(obj));
            configField.groupOrder = groupOrder;
            configField.variantName = variantName;
            configField.type = field.getType().getSimpleName();
            configField.advanced = config.advance();
            configField.group = config.group();
            configFieldList.add(configField);
            continue;
        }

        ConfigGroup configGroup = field.getAnnotation(ConfigGroup.class);
        if (null != configGroup) {

            Object nestedValue = field.get(object);

            if (nestedValue instanceof NamedDomainObjectContainer) {

                readConfig(((NamedDomainObjectContainer) nestedValue).maybeCreate("debug"),
                        prefix + "." + field.getName() + ".debug", configFieldList, configGroup.order(),
                        "debug");
                readConfig(((NamedDomainObjectContainer) nestedValue).maybeCreate("release"),
                        prefix + "." + field.getName() + ".release", configFieldList, configGroup.order(),
                        "release");
            } else {

                readConfig(nestedValue, prefix + "." + field.getName(), configFieldList, configGroup.order(),
                        "");
            }
        }
    }
}

From source file:com.hurence.logisland.util.string.StringUtilsTest.java

/**
 * Sets an environment variable FOR THE CURRENT RUN OF THE JVM
 * Does not actually modify the system's environment variables,
 *  but rather only the copy of the variables that java has taken,
 *  and hence should only be used for testing purposes!
 * @param key The Name of the variable to set
 * @param value The value of the variable to set
 */// w w  w  . ja  v  a2s . c  o  m
@SuppressWarnings("unchecked")
public static <K, V> void setEnv(final String key, final String value) throws InvocationTargetException {
    try {
        /// we obtain the actual environment
        final Class<?> processEnvironmentClass = Class.forName("java.lang.ProcessEnvironment");
        final Field theEnvironmentField = processEnvironmentClass.getDeclaredField("theEnvironment");
        final boolean environmentAccessibility = theEnvironmentField.isAccessible();
        theEnvironmentField.setAccessible(true);

        final Map<K, V> env = (Map<K, V>) theEnvironmentField.get(null);

        if (SystemUtils.IS_OS_WINDOWS) {
            // This is all that is needed on windows running java jdk 1.8.0_92
            if (value == null) {
                env.remove(key);
            } else {
                env.put((K) key, (V) value);
            }
        } else {
            // This is triggered to work on openjdk 1.8.0_91
            // The ProcessEnvironment$Variable is the key of the map
            final Class<K> variableClass = (Class<K>) Class.forName("java.lang.ProcessEnvironment$Variable");
            final Method convertToVariable = variableClass.getMethod("valueOf", String.class);
            final boolean conversionVariableAccessibility = convertToVariable.isAccessible();
            convertToVariable.setAccessible(true);

            // The ProcessEnvironment$Value is the value fo the map
            final Class<V> valueClass = (Class<V>) Class.forName("java.lang.ProcessEnvironment$Value");
            final Method convertToValue = valueClass.getMethod("valueOf", String.class);
            final boolean conversionValueAccessibility = convertToValue.isAccessible();
            convertToValue.setAccessible(true);

            if (value == null) {
                env.remove(convertToVariable.invoke(null, key));
            } else {
                // we place the new value inside the map after conversion so as to
                // avoid class cast exceptions when rerunning this code
                env.put((K) convertToVariable.invoke(null, key), (V) convertToValue.invoke(null, value));

                // reset accessibility to what they were
                convertToValue.setAccessible(conversionValueAccessibility);
                convertToVariable.setAccessible(conversionVariableAccessibility);
            }
        }
        // reset environment accessibility
        theEnvironmentField.setAccessible(environmentAccessibility);

        // we apply the same to the case insensitive environment
        final Field theCaseInsensitiveEnvironmentField = processEnvironmentClass
                .getDeclaredField("theCaseInsensitiveEnvironment");
        final boolean insensitiveAccessibility = theCaseInsensitiveEnvironmentField.isAccessible();
        theCaseInsensitiveEnvironmentField.setAccessible(true);
        // Not entirely sure if this needs to be casted to ProcessEnvironment$Variable and $Value as well
        final Map<String, String> cienv = (Map<String, String>) theCaseInsensitiveEnvironmentField.get(null);
        if (value == null) {
            // remove if null
            cienv.remove(key);
        } else {
            cienv.put(key, value);
        }
        theCaseInsensitiveEnvironmentField.setAccessible(insensitiveAccessibility);
    } catch (final ClassNotFoundException | NoSuchMethodException | IllegalAccessException
            | InvocationTargetException e) {
        throw new IllegalStateException("Failed setting environment variable <" + key + "> to <" + value + ">",
                e);
    } catch (final NoSuchFieldException e) {
        // we could not find theEnvironment
        final Map<String, String> env = System.getenv();
        Stream.of(Collections.class.getDeclaredClasses())
                // obtain the declared classes of type $UnmodifiableMap
                .filter(c1 -> "java.util.Collections$UnmodifiableMap".equals(c1.getName())).map(c1 -> {
                    try {
                        return c1.getDeclaredField("m");
                    } catch (final NoSuchFieldException e1) {
                        throw new IllegalStateException("Failed setting environment variable <" + key + "> to <"
                                + value + "> when locating in-class memory map of environment", e1);
                    }
                }).forEach(field -> {
                    try {
                        final boolean fieldAccessibility = field.isAccessible();
                        field.setAccessible(true);
                        // we obtain the environment
                        final Map<String, String> map = (Map<String, String>) field.get(env);
                        if (value == null) {
                            // remove if null
                            map.remove(key);
                        } else {
                            map.put(key, value);
                        }
                        // reset accessibility
                        field.setAccessible(fieldAccessibility);
                    } catch (final ConcurrentModificationException e1) {
                        // This may happen if we keep backups of the environment before calling this method
                        // as the map that we kept as a backup may be picked up inside this block.
                        // So we simply skip this attempt and continue adjusting the other maps
                        // To avoid this one should always keep individual keys/value backups not the entire map
                        System.out.println("Attempted to modify source map: " + field.getDeclaringClass() + "#"
                                + field.getName() + e1);
                    } catch (final IllegalAccessException e1) {
                        throw new IllegalStateException("Failed setting environment variable <" + key + "> to <"
                                + value + ">. Unable to access field!", e1);
                    }
                });
    }
    System.out.println(
            "Set environment variable <" + key + "> to <" + value + ">. Sanity Check: " + System.getenv(key));
}