Example usage for java.lang Class getField

List of usage examples for java.lang Class getField

Introduction

In this page you can find the example usage for java.lang Class getField.

Prototype

@CallerSensitive
public Field getField(String name) throws NoSuchFieldException, SecurityException 

Source Link

Document

Returns a Field object that reflects the specified public member field of the class or interface represented by this Class object.

Usage

From source file:org.apache.hupa.server.guice.GuiceServletConfig.java

@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
    servletContextRealPath = servletContextEvent.getServletContext().getRealPath("/");

    // We get the mock classes using reflection, so as we can package Hupa without mock stuff.
    try {/*  w  w w.j  ava2s .  c  o  m*/
        Class<?> mockConstants = Class.forName("org.apache.hupa.server.mock.MockConstants");
        demoProperties = (Properties) mockConstants.getField("mockProperties").get(null);
        demoHostName = demoProperties.getProperty("IMAPServerAddress");
    } catch (Exception noDemoAvailable) {
    }

    super.contextInitialized(servletContextEvent);
}

From source file:org.apache.hupa.server.ioc.GuiceListener.java

@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
    servletContextRealPath = servletContextEvent.getServletContext().getRealPath("/");

    // We get the mock classes using reflection, so as we can package Hupa
    // without mock stuff.
    try {/*from w  ww.j a  va2s  .co m*/
        Class<?> mockConstants = Class.forName("org.apache.hupa.server.mock.MockConstants");
        demoProperties = (Properties) mockConstants.getField("mockProperties").get(null);
        demoHostName = demoProperties.getProperty("IMAPServerAddress");
    } catch (Exception noDemoAvailable) {
    }

    super.contextInitialized(servletContextEvent);
}

From source file:com.kamuda.common.exception.ExceptionUtils.java

/**
 * <p>Checks whether this <code>Throwable</code> class can store a cause.</p>
 * //from   ww  w .  j ava2 s . co m
 * <p>This method does <b>not</b> check whether it actually does store a cause.<p>
 *
 * @param throwable  the <code>Throwable</code> to examine, may be null
 * @return boolean <code>true</code> if nested otherwise <code>false</code>
 * @since 2.0
 */
public static boolean isNestedThrowable(Throwable throwable) {
    if (throwable == null) {
        return false;
    }

    if (throwable instanceof Nestable) {
        return true;
    } else if (throwable instanceof SQLException) {
        return true;
    } else if (throwable instanceof InvocationTargetException) {
        return true;
    } else if (isThrowableNested()) {
        return true;
    }

    Class cls = throwable.getClass();
    for (int i = 0, isize = CAUSE_METHOD_NAMES.length; i < isize; i++) {
        try {
            Method method = cls.getMethod(CAUSE_METHOD_NAMES[i], null);
            if (method != null && Throwable.class.isAssignableFrom(method.getReturnType())) {
                return true;
            }
        } catch (NoSuchMethodException ignored) {
        } catch (SecurityException ignored) {
        }
    }

    try {
        Field field = cls.getField("detail");
        if (field != null) {
            return true;
        }
    } catch (NoSuchFieldException ignored) {
    } catch (SecurityException ignored) {
    }

    return false;
}

From source file:name.chenyuelin.aopAdvisor.DebugLoggerAdvisor.java

private Log getLog(Object target) throws IllegalArgumentException, SecurityException, IllegalAccessException {
    Class<?> targetClass = target.getClass();
    Log log = logMap.get(targetClass);//  w w w . j ava2  s.c o  m
    if (log == null) {
        try {
            log = (Log) targetClass.getField(LOG_NAME).get(null);
            logMap.put(targetClass, log);
        } catch (NoSuchFieldException e) {
            LOG.warn(e);
            return null;
        } catch (IllegalArgumentException e) {
            throw e;
        } catch (SecurityException e) {
            throw e;
        } catch (IllegalAccessException e) {
            throw e;
        }
    }
    return log;
}

From source file:org.apache.tika.parser.ner.corenlp.CoreNLPNERecogniser.java

/**
 * Creates a NERecogniser by loading model from given path
 * @param modelPath path to NER model file
 *///  w w w  .j  av  a 2 s. c  om
public CoreNLPNERecogniser(String modelPath) {
    try {
        Properties props = new Properties();
        Class<?> classifierClass = Class.forName(CLASSIFIER_CLASS_NAME);
        Method loadMethod = classifierClass.getMethod("getClassifier", String.class, Properties.class);
        classifierInstance = loadMethod.invoke(classifierClass, modelPath, props);
        classifyMethod = classifierClass.getMethod("classifyToCharacterOffsets", String.class);

        //these fields are for accessing result
        Class<?> tripleClass = Class.forName("edu.stanford.nlp.util.Triple");
        this.firstField = tripleClass.getField("first");
        this.secondField = tripleClass.getField("second");
        this.thirdField = tripleClass.getField("third");
        this.available = true;
    } catch (Exception e) {
        LOG.warn("{} while trying to load the model from {}", e.getMessage(), modelPath);
    }
    LOG.info("Available for service ? {}", available);
}

From source file:org.apache.axiom.util.stax.dialect.StAXDialectDetector.java

private static StAXDialect detectDialectFromClasses(ClassLoader classLoader, URL rootUrl) {
    Class cls;

    // Try Sun's implementation found in JREs
    cls = loadClass(classLoader, rootUrl, "com.sun.xml.internal.stream.XMLOutputFactoryImpl");
    if (cls != null) {
        // Check if the implementation has the bug fixed here:
        // https://sjsxp.dev.java.net/source/browse/sjsxp/zephyr/src/com/sun/xml/stream/ZephyrWriterFactory.java?rev=1.8&r1=1.4&r2=1.5
        boolean isUnsafeStreamResult;
        try {//  w  ww.ja v  a  2s.  c  om
            cls.getDeclaredField("fStreamResult");
            isUnsafeStreamResult = true;
        } catch (NoSuchFieldException ex) {
            isUnsafeStreamResult = false;
        }
        return new SJSXPDialect(isUnsafeStreamResult);
    }

    // Try IBM's XL XP-J
    cls = loadClass(classLoader, rootUrl, "com.ibm.xml.xlxp.api.stax.StAXImplConstants");
    if (cls != null) {
        boolean isSetPrefixBroken;
        try {
            cls.getField("IS_SETPREFIX_BEFORE_STARTELEMENT");
            isSetPrefixBroken = false;
        } catch (NoSuchFieldException ex) {
            isSetPrefixBroken = true;
        }
        return new XLXP1Dialect(isSetPrefixBroken);
    }
    cls = loadClass(classLoader, rootUrl, "com.ibm.xml.xlxp2.api.stax.StAXImplConstants");
    if (cls != null) {
        return new XLXP2Dialect();
    }

    return null;
}

From source file:nl.nn.adapterframework.extensions.ifsa.jms.IfsaMessagingSourceFactory.java

protected String getProviderUrl() {
    String purl = IFSAConstants.IFSA_BAICNF;
    log.info("IFSA ProviderURL at time of compilation [" + purl + "]");
    try {//from www .  ja v  a  2 s  .c  om
        Class clazz = Class.forName("com.ing.ifsa.IFSAConstants");
        Field baicnfField;
        try {
            baicnfField = clazz.getField("IFSA_BAICNF");
            Object baicnfFieldValue = baicnfField.get(null);
            log.info("IFSA ProviderURL specified by installed API [" + baicnfFieldValue + "]");
            purl = baicnfFieldValue.toString();
        } catch (NoSuchFieldException e1) {
            log.info("field [com.ing.ifsa.IFSAConstants.IFSA_BAICNF] not found, assuming IFSA Version 2.0");
            preJms22Api = true;
            purl = IFSA_PROVIDER_URL_V2_0;
        }
    } catch (Exception e) {
        log.warn("exception determining IFSA ProviderURL", e);
    }
    log.info("IFSA ProviderURL used to connect [" + purl + "]");
    return purl;
}

From source file:org.nanoframework.core.plugins.defaults.module.JedisModule.java

@Override
public List<Module> load() throws Throwable {
    try {//  w  w w  . j  a  v  a  2 s .c  o  m
        final Class<?> redisClientPool = Class.forName("org.nanoframework.orm.jedis.RedisClientPool");
        final long time = System.currentTimeMillis();
        final Object pool = redisClientPool.getField("POOL").get(redisClientPool);
        pool.getClass().getMethod("initRedisConfig", List.class).invoke(pool, properties);
        pool.getClass().getMethod("createJedis").invoke(pool);
        pool.getClass().getMethod("bindGlobal").invoke(pool);
        LOGGER.info("Redis?, : " + (System.currentTimeMillis() - time) + "ms");
    } catch (final Throwable e) {
        if (!(e instanceof ClassNotFoundException)) {
            throw new PluginLoaderException(e.getMessage(), e);
        }

    }

    return modules;
}

From source file:com.efithealth.app.activity.BaseActivity.java

@Override
protected void onCreate(Bundle arg0) {
    super.onCreate(arg0);

    // ????/*from w w w.j a v a2  s  .  co m*/
    Window window = getWindow();
    Class<? extends Window> clazz = window.getClass();
    int tranceFlag = 0;
    int darkModeFlag = 0;
    Class<?> layoutParams;
    try {
        layoutParams = Class.forName("android.view.MiuiWindowManager$LayoutParams");
        Field field = layoutParams.getField("EXTRA_FLAG_STATUS_BAR_TRANSPARENT");
        tranceFlag = field.getInt(layoutParams);
        field = layoutParams.getField("EXTRA_FLAG_STATUS_BAR_DARK_MODE");
        darkModeFlag = field.getInt(layoutParams);
        Method extraFlagField = clazz.getMethod("setExtraFlags", int.class, int.class);
        // ?????
        // extraFlagField.invoke(window, tranceFlag, tranceFlag);
        // ???
        extraFlagField.invoke(window, tranceFlag | darkModeFlag, tranceFlag | darkModeFlag);
        // 
        // extraFlagField.invoke(window, 0, darkModeFlag);
    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:Main.java

/**
 * invoke the leftParameter and get the name property.
 * it will try the Array.length() and Map.get(),
 * then it will try get'Name' and is'Name',
 * last, it will to find the name by invoke field.
 *//*from  ww  w  .  jav a  2s  . c om*/
public static Object searchProperty(Object leftParameter, String name) throws Exception {
    Class<?> leftClass = leftParameter.getClass();
    Object result;
    if (leftParameter.getClass().isArray() && "length".equals(name)) {
        result = Array.getLength(leftParameter);
    } else if (leftParameter instanceof Map) {
        result = ((Map<Object, Object>) leftParameter).get(name);
    } else {
        try {
            String getter = "get" + name.substring(0, 1).toUpperCase() + name.substring(1);
            Method method = leftClass.getMethod(getter, new Class<?>[0]);
            if (!method.isAccessible()) {
                method.setAccessible(true);
            }
            result = method.invoke(leftParameter, new Object[0]);
        } catch (NoSuchMethodException e2) {
            try {
                String getter = "is" + name.substring(0, 1).toUpperCase() + name.substring(1);
                Method method = leftClass.getMethod(getter, new Class<?>[0]);
                if (!method.isAccessible()) {
                    method.setAccessible(true);
                }
                result = method.invoke(leftParameter, new Object[0]);
            } catch (NoSuchMethodException e3) {
                Field field = leftClass.getField(name);
                result = field.get(leftParameter);
            }
        }
    }
    return result;
}