Example usage for java.lang.reflect Field get

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

Introduction

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

Prototype

@CallerSensitive
@ForceInline 
public Object get(Object obj) throws IllegalArgumentException, IllegalAccessException 

Source Link

Document

Returns the value of the field represented by this Field , on the specified object.

Usage

From source file:HTMLColors.java

/** Returns a color with the specified case-insensitive name. */
private static Color getColorFromField(String name) {
    try {// w  w  w.ja  v a  2 s  .  c  om
        Field colorField = HTMLColors.class.getField(name.toLowerCase());
        return (Color) colorField.get(HTMLColors.class);
    } catch (NoSuchFieldException exc) {
    } catch (SecurityException exc) {
    } catch (IllegalAccessException exc) {
    } catch (IllegalArgumentException exc) {
    }
    return null;
}

From source file:ml.dmlc.xgboost4j.java.NativeLibLoader.java

/**
 * Add libPath to java.library.path, then native library in libPath would be load properly
 *
 * @param libPath library path/*w ww. j  a  v  a2s.  c  om*/
 * @throws IOException exception
 */
private static void addNativeDir(String libPath) throws IOException {
    try {
        Field field = ClassLoader.class.getDeclaredField("usr_paths");
        field.setAccessible(true);
        String[] paths = (String[]) field.get(null);
        for (String path : paths) {
            if (libPath.equals(path)) {
                return;
            }
        }
        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: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);//from  ww w.j a  v  a  2 s  .  c  o  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.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  a va 2s .  co 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:com.vmware.photon.controller.common.dcp.BasicServiceHost.java

private static String buildPath(Class<? extends Service> type) {
    try {//from   w ww .  java2 s .c  o  m
        Field f = type.getField(FIELD_NAME_SELF_LINK);
        return (String) f.get(null);
    } catch (NoSuchFieldException | IllegalAccessException e) {
        Utils.log(Utils.class, Utils.class.getSimpleName(), Level.SEVERE, "%s field not found in class %s: %s",
                FIELD_NAME_SELF_LINK, type.getSimpleName(), Utils.toString(e));
        throw new IllegalArgumentException(e);
    }
}

From source file:com.dianping.lion.util.BeanUtils.java

@SuppressWarnings("unchecked")
public static <T> T getDeclaredFieldValue(Object object, String propertyName) throws NoSuchFieldException {
    Assert.notNull(object);/*from   w  w  w .j ava2  s. c  om*/
    Assert.hasText(propertyName);

    Field field = getDeclaredField(object.getClass(), propertyName);

    boolean accessible = field.isAccessible();
    Object result = null;
    synchronized (field) {
        field.setAccessible(true);
        try {
            result = field.get(object);
        } catch (IllegalAccessException e) {
            throw new NoSuchFieldException("No such field: " + object.getClass() + '.' + propertyName);
        } finally {
            field.setAccessible(accessible);
        }
    }
    return (T) result;
}

From source file:io.apiman.gateway.engine.es.ESClientFactory.java

/**
 * Creates a cache by looking it up in a static field.  Typically used for
 * testing./*ww  w.ja v a 2s.  c  o  m*/
 * @param className the class name
 * @param fieldName the field name
 * @param indexName the name of the ES index
 * @return the ES client
 */
public static JestClient createLocalClient(String className, String fieldName, String indexName) {
    String clientKey = "local:" + className + '/' + fieldName; //$NON-NLS-1$
    synchronized (clients) {
        if (clients.containsKey(clientKey)) {
            return clients.get(clientKey);
        } else {
            try {
                Class<?> clientLocClass = Class.forName(className);
                Field field = clientLocClass.getField(fieldName);
                JestClient client = (JestClient) field.get(null);
                clients.put(clientKey, client);
                initializeClient(client, indexName);
                return client;
            } catch (ClassNotFoundException | NoSuchFieldException | SecurityException
                    | IllegalArgumentException | IllegalAccessException e) {
                throw new RuntimeException("Error using local elasticsearch client.", e); //$NON-NLS-1$
            }
        }
    }
}

From source file:com.github.sumimakito.quickkv.util.DataProcessor.java

public static void printFieldsOfObject(Object object) {
    System.out.println("[Fields of Object: " + object.getClass().getSimpleName() + "]");
    for (Field field : object.getClass().getDeclaredFields()) {
        field.setAccessible(true); // You might want to set modifier to public first.
        Object value = null;/*from  www  .  j  a  v  a 2 s.c  o m*/
        try {
            value = field.get(object);
            if (value != null) {
                System.out.println("- (" + value.getClass().getSimpleName() + ")[" + field.getName() + "]=["
                        + value + "]");
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }
}

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

/**
 * Retrieves the specified property of type {@link ImmutableList}
 */// w ww.  j  a  v a 2s.co  m
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();
    }
}

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//  w w  w.ja  v  a  2  s . c  om
 * @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");
    }
}