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:com.pinterest.deployservice.common.ChangeFeedJob.java

private static String getConfigChangeMessage(Object ori, Object cur) {
    if (ori.getClass() != cur.getClass())
        return null;

    List<String> results = new ArrayList<>();
    try {/*from  w  ww . j av a  2 s.  c o  m*/
        if (ori instanceof List) {
            // Process list of custom object and others (e.g. List<String>)
            List<?> originalList = (List<?>) ori;
            List<?> currentList = (List<?>) cur;
            for (int i = 0; i < Math.max(originalList.size(), currentList.size()); i++) {
                Object originalItem = i < originalList.size() ? originalList.get(i) : null;
                Object currentItem = i < currentList.size() ? currentList.get(i) : null;
                if (!Objects.equals(originalItem, currentItem)) {
                    Object temp = originalItem != null ? originalItem : currentItem;
                    if (temp.getClass().getName().startsWith("com.pinterest")) {
                        results.add(String.format("%-40s  %-40s  %-40s%n", i,
                                toStringRepresentation(originalItem), toStringRepresentation(currentItem)));
                    } else {
                        results.add(String.format("%-40s  %-40s  %-40s%n", i, originalItem, currentItem));
                    }
                }
            }
        } else if (ori instanceof Map) {
            // Process Map (e.g. Map<String, String>)
            Map<?, ?> originalMap = (Map<?, ?>) ori;
            Map<?, ?> currentMap = (Map<?, ?>) cur;
            Set<String> keys = new HashSet<>();
            originalMap.keySet().stream().forEach(key -> keys.add((String) key));
            currentMap.keySet().stream().forEach(key -> keys.add((String) key));
            for (String key : keys) {
                Object originalItem = originalMap.get(key);
                Object currentItem = currentMap.get(key);
                if (!Objects.equals(originalItem, currentItem)) {
                    results.add(String.format("%-40s  %-40s  %-40s%n", key, originalItem, currentItem));
                }
            }
        } else {
            // Process other objects (e.g. custom object bean)
            Field[] fields = ori.getClass().getDeclaredFields();
            for (Field field : fields) {
                field.setAccessible(true);
                Object oriObj = field.get(ori);
                Object curObj = field.get(cur);
                if (!Objects.equals(oriObj, curObj)) {
                    if (oriObj instanceof List) {
                        results.add(String.format("%-40s  %-40s  %-40s%n", field.getName(),
                                toStringRepresentation(oriObj), toStringRepresentation(curObj)));
                    } else {
                        results.add(String.format("%-40s  %-40s  %-40s%n", field.getName(), oriObj, curObj));
                    }

                }
            }
        }
    } catch (Exception e) {
        LOG.error("Failed to get config message.", e);
    }

    if (results.isEmpty()) {
        return null;
    }

    StringBuilder resultBuilder = new StringBuilder();
    resultBuilder.append(String.format("%n%-40s  %-40s  %-40s%n", "Name", "Original Value", "Current Value"));
    results.stream().forEach(resultBuilder::append);
    return resultBuilder.toString();
}

From source file:hivemall.xgboost.NativeLibLoader.java

/**
 * Add libPath to java.library.path, then native library in libPath would be load properly.
 *
 * @param libPath library path// ww w  .  j av  a2 s .  co m
 * @throws IOException exception
 */
private static void addLibraryPath(String libPath) throws IOException {
    try {
        final Field field = ClassLoader.class.getDeclaredField("usr_paths");
        field.setAccessible(true);
        final String[] paths = (String[]) field.get(null);
        for (String path : paths) {
            if (libPath.equals(path)) {
                return;
            }
        }
        final String[] tmp = new String[paths.length + 1];
        System.arraycopy(paths, 0, tmp, 0, paths.length);
        tmp[paths.length] = libPath;
        field.set(null, tmp);
    } catch (IllegalAccessException e) {
        logger.error(e.getMessage());
        throw new IOException("Failed to get permissions to set library path");
    } catch (NoSuchFieldException e) {
        logger.error(e.getMessage());
        throw new IOException("Failed to get field handle to set library path");
    }
}

From source file:io.tilt.minka.utils.Defaulter.java

private static PropertyEditor edit(final Properties props, final Object configurable, final Field staticField,
        final Field instanceField) throws IllegalAccessException {

    staticField.setAccessible(true);
    final String name = instanceField.getName();
    final String staticValue = staticField.get(configurable).toString();
    final Object propertyOrDefault = props.getProperty(name, System.getProperty(name, staticValue));
    final String objName = configurable.getClass().getSimpleName();
    final PropertyEditor editor = PropertyEditorManager.findEditor(instanceField.getType());
    final String setLog = "Defaulter: set <{}> field [{}] = '{}' from {} ";
    try {// www .  ja  v a2  s  .  co m
        editor.setAsText(propertyOrDefault.toString());
        logger.info(setLog, objName, name, editor.getValue(),
                propertyOrDefault != staticValue ? " property " : staticField.getName());
    } catch (Exception e) {
        logger.error(
                "Defaulter: object <{}> field: {} does not accept property or static "
                        + "default value: {} (reason: {})",
                objName, name, propertyOrDefault, e.getClass().getSimpleName());
        try { // at this moment only prop. might've been failed
            editor.setAsText(staticValue);
            logger.info(setLog, objName, name, editor.getValue(), staticField.getName());
        } catch (Exception e2) {
            final StringBuilder sb = new StringBuilder().append("Defaulter: object <").append(objName)
                    .append("> field: ").append(name).append(" does not accept static default value: ")
                    .append(propertyOrDefault).append(" (reason: ").append(e.getClass().getSimpleName())
                    .append(")");
            throw new RuntimeException(sb.toString());
        }

    }

    return editor;
}

From source file:com.taobao.tdhs.client.protocol.TDHSProtocolBinary.java

protected static void encodeRequest(Request o, ByteArrayOutputStream out, String charsetName)
        throws IllegalAccessException, IOException, TDHSEncodeException {
    for (Field f : o.getClass().getDeclaredFields()) {
        if (!Modifier.isPublic(f.getModifiers())) {
            f.setAccessible(true);
        }// w w  w .  ja v  a 2  s .  co m
        Object v = f.get(o);
        if (v instanceof Request) {
            encodeRequest((Request) v, out, charsetName);
        } else if (f.getName().startsWith("_")) {
            writeObjectToStream(v, out, f.getName(), charsetName);
        }
    }
}

From source file:com.spotify.helios.client.DefaultHttpConnector.java

private static void setRequestMethod(final HttpURLConnection connection, final String method,
        final boolean isHttps) {
    // Nasty workaround for ancient HttpURLConnection only supporting few methods
    final Class<?> httpURLConnectionClass = connection.getClass();
    try {/*from w  w  w  .  j a v  a  2  s  .  c  om*/
        Field methodField;
        HttpURLConnection delegate;
        if (isHttps) {
            final Field delegateField = httpURLConnectionClass.getDeclaredField("delegate");
            delegateField.setAccessible(true);
            delegate = (HttpURLConnection) delegateField.get(connection);
            methodField = delegate.getClass().getSuperclass().getSuperclass().getSuperclass()
                    .getDeclaredField("method");
        } else {
            delegate = connection;
            methodField = httpURLConnectionClass.getSuperclass().getDeclaredField("method");
        }

        methodField.setAccessible(true);
        methodField.set(delegate, method);
    } catch (NoSuchFieldException | IllegalAccessException e) {
        throw Throwables.propagate(e);
    }
}

From source file:jfix.util.Reflections.java

/**
 * Returns all fields of a given class (including fields from superclasses).
 *///w ww . ja v  a 2 s.  co  m
public static Set<Field> getFields(Class<?> clazz) {
    Set<Field> result = new HashSet<>();
    for (Class<?> superClass : getSuperClassesAndInterfaces(clazz)) {
        for (Field field : superClass.getDeclaredFields()) {
            field.setAccessible(true);
            result.add(field);
        }
    }
    return result;
}

From source file:com.github.hibatis.ReflectionUtils.java

/**
 * ?, ?DeclaredField, ?.//from  w w  w . jav  a2 s .c  o  m
 * 
 * ?Object?, null.
 */
public static Field getAccessibleField(final Object obj, final String fieldName) {
    for (Class<?> superClass = obj.getClass(); superClass != Object.class; superClass = superClass
            .getSuperclass()) {
        try {
            Field field = superClass.getDeclaredField(fieldName);
            field.setAccessible(true);
            return field;
        } catch (NoSuchFieldException e) {// NOSONAR
            // Field??,?
        }
    }
    return null;
}

From source file:com.alibaba.wasp.ipc.WaspRPC.java

static long getProtocolVersion(Class<? extends VersionedProtocol> protocol)
        throws NoSuchFieldException, IllegalAccessException {
    Field versionField = protocol.getField("VERSION");
    versionField.setAccessible(true);
    return versionField.getLong(protocol);
}

From source file:cn.loveapple.client.android.LoveappleHelper.java

private static Object getDeclaredField(Object obj, String name)
        throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
    Field f = obj.getClass().getDeclaredField(name);
    f.setAccessible(true);
    Object out = f.get(obj);/*from  w w  w.jav a 2 s  .co m*/
    Log.d(LOG_TAG, obj.getClass().getName() + "." + name + " = " + out);
    return out;
}

From source file:com.spectralogic.ds3contractcomparator.print.utils.HtmlRowGeneratorUtils.java

/**
 * Retrieves the specified property of type {@link ImmutableList}
 *//*from   w  w  w.  j ava 2s  .  com*/
public static <T, N> ImmutableList<N> getListPropertyFromObject(final Field field, final T object) {
    if (object == null) {
        return ImmutableList.of();
    }
    try {
        field.setAccessible(true);
        final Object objectField = field.get(object);
        if (objectField == null) {
            return ImmutableList.of();
        }
        if (objectField instanceof ImmutableList) {
            return (ImmutableList<N>) objectField;
        }
        throw new IllegalArgumentException(
                "Object should be of type ImmutableList, but was: " + object.getClass().toString());
    } catch (final IllegalAccessException e) {
        LOG.error("Could not retrieve list element " + field.getName() + " from object of class "
                + object.getClass().toString() + ": " + e.getMessage(), e);

        return ImmutableList.of();
    }
}