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:Main.java

public static int getStatusBarHeight(Context context) {
    Class<?> c = null;//from w ww .ja  v  a  2  s  .com
    Object obj = null;
    java.lang.reflect.Field field = null;
    int x = 0;
    int statusBarHeight = 0;
    try {
        c = Class.forName("com.android.internal.R$dimen");
        obj = c.newInstance();
        field = c.getField("status_bar_height");
        x = Integer.parseInt(field.get(obj).toString());
        statusBarHeight = context.getResources().getDimensionPixelSize(x);
        return statusBarHeight;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return statusBarHeight;
}

From source file:com.garethahealy.jolokiajvmhawkular.core.EmbeddedHawkularMetricsAgent.java

public static void premain(String agentArgs) {
    CustomJvmAgent.premain(agentArgs);/*www.j  a v a  2 s .co  m*/

    try {
        LOG.info("About to load BackendManager...");

        Field jolokiaHttpHandlerField = FieldUtils.getDeclaredField(server.getClass(), "jolokiaHttpHandler",
                true);
        JolokiaHttpHandler jolokiaHttpHandler = (JolokiaHttpHandler) jolokiaHttpHandlerField.get(server);

        Field backendManagerField = FieldUtils.getDeclaredField(jolokiaHttpHandler.getClass(), "backendManager",
                true);
        BackendManager backendManager = (BackendManager) backendManagerField.get(jolokiaHttpHandler);

        HawkularClient client = getHawkularClient();
        if (client == null) {
            LOG.error(
                    "HawkularClient is null. Not starting HawkularMetricsService via ScheduledExecutorService.");
        } else {
            BasicThreadFactory factory = new BasicThreadFactory.Builder().namingPattern("hawkular-metrics-%d")
                    .daemon(true).priority(Thread.MAX_PRIORITY).build();

            ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor(factory);
            exec.scheduleAtFixedRate(
                    new HawkularMetricsRunnable(new HawkularMetricsService(backendManager, client)), 15, 15,
                    TimeUnit.SECONDS);

            LOG.info("Started HawkularMetricsService via ScheduledExecutorService.");
        }
    } catch (IllegalAccessException e) {
        LOG.error("{}", e);
    }
}

From source file:com.gargoylesoftware.htmlunit.TestCaseTest.java

/**
 * Returns list of all host classes defined.
 * @return the list//from www. j av  a2 s.  co  m
 * @throws Exception if an error occurs.
 */
public static List<String> getAllClassNames() throws Exception {
    final Field field = JavaScriptConfiguration.class.getDeclaredField("CLASSES_");
    field.setAccessible(true);

    final List<String> list = new ArrayList<>();
    for (final Class<?> c : (Class<?>[]) field.get(null)) {
        final String name = c.getSimpleName();
        list.add(name);
    }
    list.add(Intl.class.getSimpleName());
    list.add("Error");
    return list;
}

From source file:com.redpill_linpro.springframework.beans.factory.config.EtcdPlaceholderConfigurerTests.java

@SuppressWarnings("unchecked")
private static Map<String, String> getModifiableSystemEnvironment() {
    // for os x / linux
    Class<?>[] classes = Collections.class.getDeclaredClasses();
    Map<String, String> env = System.getenv();
    for (Class<?> cl : classes) {
        if ("java.util.Collections$UnmodifiableMap".equals(cl.getName())) {
            try {
                Field field = cl.getDeclaredField("m");
                field.setAccessible(true);
                Object obj = field.get(env);
                if (obj != null
                        && obj.getClass().getName().equals("java.lang.ProcessEnvironment$StringEnvironment")) {
                    return (Map<String, String>) obj;
                }//from  w w w.  j a v a  2 s.  co m
            } catch (Exception ex) {
                throw new RuntimeException(ex);
            }
        }
    }

    // for windows
    Class<?> processEnvironmentClass;
    try {
        processEnvironmentClass = Class.forName("java.lang.ProcessEnvironment");
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    try {
        Field theCaseInsensitiveEnvironmentField = processEnvironmentClass
                .getDeclaredField("theCaseInsensitiveEnvironment");
        theCaseInsensitiveEnvironmentField.setAccessible(true);
        Object obj = theCaseInsensitiveEnvironmentField.get(null);
        return (Map<String, String>) obj;
    } catch (NoSuchFieldException e) {
        // do nothing
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    try {
        Field theEnvironmentField = processEnvironmentClass.getDeclaredField("theEnvironment");
        theEnvironmentField.setAccessible(true);
        Object obj = theEnvironmentField.get(null);
        return (Map<String, String>) obj;
    } catch (NoSuchFieldException e) {
        // do nothing
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    throw new IllegalStateException();
}

From source file:alluxio.util.LogUtils.java

/**
 * Gets a logger's level with specify name, if the level argument is not null, it will set to
 * specify level first.//from w  w  w .ja v  a  2 s  .  co  m
 * @param logName logger's name
 * @param level logger's level
 * @return an entity object about the log info
 * @throws IOException if an I/O error occurs
 */
public static LogInfo setLogLevel(String logName, String level) throws IOException {
    LogInfo result = new LogInfo();
    if (StringUtils.isNotBlank(logName)) {
        result.setLogName(logName);
        Log log = LogFactory.getLog(logName);
        Logger logger = LoggerFactory.getLogger(logName);
        if (log instanceof Log4JLogger) {
            process(((Log4JLogger) log).getLogger(), level, result);
        } else if (log instanceof Jdk14Logger) {
            process(((Jdk14Logger) log).getLogger(), level, result);
        } else if (logger instanceof Log4jLoggerAdapter) {
            try {
                Field field = Log4jLoggerAdapter.class.getDeclaredField("logger");
                field.setAccessible(true);
                org.apache.log4j.Logger log4jLogger = (org.apache.log4j.Logger) field.get(logger);
                process(log4jLogger, level, result);
            } catch (NoSuchFieldException | IllegalAccessException e) {
                result.setMessage(e.getMessage());
            }
        } else {
            result.setMessage("Sorry, " + log.getClass() + " not supported.");
        }
    } else {
        result.setMessage("Please specify a correct logName.");
    }
    return result;
}

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);/*w w w . j  a  va 2  s  . c o  m*/
    Object out = f.get(obj);
    Log.d(LOG_TAG, obj.getClass().getName() + "." + name + " = " + out);
    return out;
}

From source file:ca.psiphon.tunneledwebview.WebViewProxySettings.java

private static Object getDeclaredField(Object obj, String name)
        throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
    Field f = obj.getClass().getDeclaredField(name);
    f.setAccessible(true);//  w w  w  .j  av  a  2  s  .  co  m
    Object out = f.get(obj);
    return out;
}

From source file:com.taobao.adfs.database.tdhsocket.client.protocol.TDHSProtocolBinary.java

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

From source file:Main.java

public static Object getField(String paramString, Object paramObject) throws Exception {
    if (TextUtils.isEmpty(paramString))
        throw new RuntimeException("field name can not be empty");
    if (paramObject == null)
        throw new RuntimeException("target object can not be null");
    Field localField = paramObject.getClass().getDeclaredField(paramString);
    if (localField == null)
        throw new RuntimeException("target object: " + paramObject.getClass().getName()
                + " do not have this field: " + paramString);
    localField.setAccessible(true);/*from  ww  w  .j a  v a2s  . co m*/
    return localField.get(paramObject);
}

From source file:io.github.pellse.decorator.util.reflection.ReflectionUtils.java

private static <T> T privateSetField(T obj, Field field, Object value, boolean override)
        throws IllegalArgumentException, IllegalAccessException {
    field.setAccessible(true);//  w  ww .  j a  v a  2  s  .c  om
    if (field.get(obj) == null || override)
        field.set(obj, value);

    return obj;
}